Mocking FormsIdentity.Ticket.UserData with Moq - asp.net-mvc

As part of a unit test I am trying to mock the return value of FormsIdentity.Ticket.UserData
The following will NOT work but it should give an idea of what I am trying to do:
var principal = Mock<IPrincipal>();
var formsIdentity = Mock<FormsIdentity>();
formsIdentity.Setup(a => a.Ticket.UserData).Returns("aaa | bbb | ccc");
principal.Setup(b => b.Identity).Returns(formsIdentity.Object);
The code I am trying to test looks something like this:
FormsIdentity fIdentity = HttpContext.Current.User.Identity as FormsIdentity;
string userData = fIdentity.Ticket.UserData;
All I want to do in my unit test is fake the return value from FormsIdentity.Ticket.UserData. But when I run the code in the first section I get an error when trying to mock the FormsIdentity. The error says the type to mock must be an interface, abstract class or non-sealed class.
I tried to use IIdentity instead of FormsIdentity (FormsIdentity is an implementation of IIdentity) but IIdentity doesn't have .Ticket.UserData.
So how can I write this test so that I get a value from FormsIdentity.Ticket.UserData?

I'm not a Unit Test expert, by any means, just getting my feet wet in the area.
Isn't it overkill to mock out the Identity in a unit test, because the Identity code is code that you can assume works already in isolation? (ie. it's Microsoft's code?) For example, when unit testing your own code, you wouldn't need to mock out one of the Framework objects. I mean, would you ever need to mock a List or a Dictionary?
That being said, if you REALLY want to test your code in isolation or for some reason have super fine control over the data returned in Userdata, can't you just write an Interface for the interaction between the Identity and your code?
Public Interface IIdentityUserData
Readonly Property UserData As String
End Interface
Public Class RealIdentityWrapper
Implements IIdentityUserData
Private _identity as FormsIdentity
Public Sub New(identity as FormsIdentity)
'the real version takes in the actual forms identity object
_identity = identity
End Sub
Readonly Property UserData As String Implements IIDentityUserData.UserData
If not _identity is nothing then
Return _identity.Ticket.UserData
End If
End Property
End Class
'FAKE CLASS...use this instead of Mock
Public Class FakeIdentityWrapper
Implements IIdentityUserData
Readonly Property UserData As String Implements IIDentityUserData.UserData
If not _identity is nothing then
Return "whatever string you want"
End If
End Property
End Class
'here's the code that you're trying to test...modified slightly
Dim fIdentity As FormsIdentity= HttpContext.Current.User.Identity
Dim identityUserData As IIdentityUserData
identityUserData =
'TODO: Either the Real or Fake implementation. If testing, inject the Fake implementation. If in production, inject the Real implementation
Dim userData as String
userData = identityUserData.UserData
Hope this helps

Related

Why does asp.net core support several ways for registering a service?

I will create a service StudentData from class Student:
public interface IStudentData
{
List<Student> GetAll();
}
public class StudentData : IStudentData
{
public List<Student> GetAll()
{
var students = new List<Student>
{
new Student { FirstName = "Harry", LastName = "Potter" },
new Student { FirstName = "Hermione", LastName = "Granger" }
};
return students;
}
}
public class Student
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
Here is some ways to register the service:
services.AddTransient<IStudentData, StudentData>();
services.AddTransient(typeof(IStudentData), typeof(StudentData));
services.Add(new ServiceDescriptor(typeof(IStudentData), typeof(StudentData), ServiceLifetime.Transient));
services.Add(new ServiceDescriptor(typeof(IStudentData), p => new StudentData(), ServiceLifetime.Transient));
services.AddSingleton<IStudentData, StudentData>();
services.AddSingleton(typeof(IStudentData), typeof(StudentData));
services.Add(new ServiceDescriptor(typeof(IStudentData), typeof(StudentData), ServiceLifetime.Singleton));
services.Add(new ServiceDescriptor(typeof(IStudentData), p => new StudentData(), ServiceLifetime.Singleton));
services.AddScoped<IStudentData, StudentData>();
services.AddScoped(typeof(IStudentData), typeof(StudentData));
services.Add(new ServiceDescriptor(typeof(IStudentData), typeof(StudentData), ServiceLifetime.Scoped));
services.Add(new ServiceDescriptor(typeof(IStudentData), p => new StudentData(), ServiceLifetime.Scoped));
services.AddInstance<IStudentData>(new StudentData());
services.AddInstance(typeof(IStudentData), new StudentData());
services.Add(new ServiceDescriptor(typeof(IStudentData), new StudentData()));
So, when to use the first/second/thirth...?
Sub-question: Is there another way to register a service?
The reason that there are multiple ways of configuring the same thing is simply for convenience and to make it flexible and descriptive to the extent of the C# language.
// These are the same, you're just specifying the types and the lifetime:
services.AddTransient<IStudentData, StudentData>();
services.AddTransient(typeof(IStudentData), typeof(StudentData));
In the above declarations, it is descriptive and convenient to simply provide the interface type and the concrete service implementation type - but it is achievable through the C# language in multiple ways. The first making use of generic type parameters, the second constructor parameters.
The following declarations are also the same, as they are currently written, but are made more flexible because the Add method accepts a ServiceDescriptor object, which has even more overloads for added flexibility.
// These are doing the same thing, they just configure the resolution of the interface to a bog standard instance of the StudentData class.
services.Add(new ServiceDescriptor(typeof(IStudentData), typeof(StudentData), ServiceLifetime.Transient));
services.Add(new ServiceDescriptor(typeof(IStudentData), p => new StudentData(), ServiceLifetime.Transient));
I'll take the last example that you gave (immediately above) and explain a simple use case to show the flexibility of it:
Imagine that the class StudentData accepts the current HttpContext as a constructor parameter (it is a dependency of the class). I could configure it so that whenever an instance of type IStudentData is resolved to StudentData, that it is resolved with the current HttpContext passed into the constructor.
// Passing in the current HttpContext into StudentData
services.Add(new ServiceDescriptor(typeof(IStudentData), p => new StudentData(HttpContext.Current), ServiceLifetime.Transient));
But it's not just limited to passing in specific values, you can provide any method that returns an instance of your class (a factory) - so the possibilities are endless (sort of).
There is no right or wrong one to choose when configuring your dependencies, but I would recommend choosing the one that makes it most clear what is being configured.
You can find more info about dependency injection here: https://docs.asp.net/en/latest/fundamentals/dependency-injection.html
For ex: Singleton, means that you will create your service once, and then, use the same instance during all application's life-cicle
A general rule of thumb is, if you know the type at compile time, use the generic version services.AddTransient<IStudentData, StudentData>();.
When you don't know the type ahead of compile time, i.e. when you iterate through the assembly via reflection and get all types which implement a certain interface, you use the non-generic version, because you can't use generics in this case.
foreach(var type in GetAllOfSomeInterface()) {
services.AddTransient(typeof(ISomeInterface), type);
}
Use the Func<IServiceProvider, T> ones when you need a factory method to resolve stuff that you can't otherwise via DI, i.e. a setting or option that's determined when the application starts and you can't use IOptions<T> (i.e. third party library where you can't change the class to accept the options DI pattern).
Use services.Add when you create your own dependency injection system and the overloads for it, or when you need to dynamically determine the scope (Transient, Scoped or Singleton), usually used when you wrap around an existing IoC container. You'll rarely use that though.

MVC 5 Identity 2 - customer UserStore methods not being called

I am trying to implement a custom UserStore for my MVC 5 application so that I can delegate the database commands to my existing database project.
The tables in my database use integer keys, so I created a custom UserManager that inherits UserManager<User, int> instead of just UserManager<User>. For that reason, I also created a custom UserStore that implements IUserPasswordStore<User, int> instead of just IUserPasswordStore<User>.
Briefly:
public class CustomUserManager : UserManager<User, int>
{
public CustomUserManager(CustomUserStore store) : base(store)
{
}
}
public class CustomUserStore : IUserPasswordStore<User, int>
{
private readonly DbContext _db;
public CustomUserStore(DbContext db)
{
_db = db;
}
public Task<User> FindByIdAsync(int userId)
{
return _db.users.SingleOrDefaultAsync(u => u.Id == userId);
}
public Task UpdateAsync(User user)
{
_db.Entry(user).State = System.Data.Entity.EntityState.Modified;
return _db.SaveChangesAsync();
}
}
Now, it seems that when I call UpdateAsync on CustomUserManager, it does not go through my custom CustomUserStore, but rather through some default implementation or something. The problem is evident because CustomUserManager.UpdateAsync() returns Task<IdentityResult>, while my implementation in CustomUserStore returns just Task. Hence there are no errors or anything, but the method is not being called. I think IUserPasswordStore<User, int> should have some method UpdateAsync that returns Task<IdentityResult> but it doesn't...
On the other hand, the FindByIdAsync method does work fine and calls the method in my CustomUserStore.
I am quite sure the problem is due to inheriting the classes with the custom key type (int in my case). Any example of a custom UserStore I can find online just uses the string keys and does not inherit IUserStore<User, int> but just IUserStore<User>.
However I can't figure out my problem. Perhaps I can just override all the methods in my CustomUserManager but that seems like a work-around rather than a solution. Is this a bug in the framework perhaps, I think the custom key types is still relatively new or even in alpha?
I know that this is an old question but I struggled yesterday with the same issue and after some time spent on it, I decided to take a look in the Identity source code and what I've found, almost made me smashed my head against the wall...
Simple, if you call UserManager.UpdateAsync, in the base class you will see that before the UserStore.UpdateAsync there is a validation that takes place, which, in my case, failed (doesn't matter the reason). So, please, be so kind and check in your class (controller class) the result of UpdateAsync which is an IdentityResult and more then sure the Succes result is false.
Evdin

Problem Implementing StructureMap in VB.Net Conversion of SharpArchitecture

I work in a VB.Net environment and have recently been tasked with creating an MVC environment to use as a base to work from. I decided to convert the latest SharpArchitecture release (Q3 2009) into VB, which on the whole has gone fine after a bit of hair pulling. I came across a problem with Castle Windsor where my custom repository interface (lives in the core/domain project) that was reference in the constructor of my test controller was not getting injected with the concrete implementation (from the data project). I hit a brick wall with this so basically decided to switch out Castle Windsor for StructureMap.
I think I have implemented this ok as everything compiles and runs and my controller ran ok when referencing a custom repository interface. It appears now that I have/or cannot now setup my generic interfaces up properly (I hope this makes sense so far as I am new to all this). When I use IRepository(Of T) (wanting it to be injected with a concrete implementation of Repository(Of Type)) in the controller constructor I am getting the following runtime error:
"StructureMap Exception Code: 202 No Default Instance defined for PluginFamily SharpArch.Core.PersistenceSupport.IRepository`1[[DebtRemedy.Core.Page, DebtRemedy.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], SharpArch.Core, Version=1.0.0.0, Culture=neutral, PublicKeyToken=b5f559ae0ac4e006"
Here are my code excerpts that I am using (my project is called DebtRemedy).
My structuremap registry class
Public Class DefaultRegistry
Inherits Registry
Public Sub New()
''//Generic Repositories
AddGenericRepositories()
''//Custom Repositories
AddCustomRepositories()
''//Application Services
AddApplicationServices()
''//Validator
[For](GetType(IValidator)).Use(GetType(Validator))
End Sub
Private Sub AddGenericRepositories()
''//ForRequestedType(GetType(IRepository(Of ))).TheDefaultIsConcreteType(GetType(Repository(Of )))
[For](GetType(IEntityDuplicateChecker)).Use(GetType(EntityDuplicateChecker))
[For](GetType(IRepository(Of ))).Use(GetType(Repository(Of )))
[For](GetType(INHibernateRepository(Of ))).Use(GetType(NHibernateRepository(Of )))
[For](GetType(IRepositoryWithTypedId(Of ,))).Use(GetType(RepositoryWithTypedId(Of ,)))
[For](GetType(INHibernateRepositoryWithTypedId(Of ,))).Use(GetType(NHibernateRepositoryWithTypedId(Of ,)))
End Sub
Private Sub AddCustomRepositories()
Scan(AddressOf SetupCustomRepositories)
End Sub
Private Shared Sub SetupCustomRepositories(ByVal y As IAssemblyScanner)
y.Assembly("DebtRemedy.Core")
y.Assembly("DebtRemedy.Data")
y.WithDefaultConventions()
End Sub
Private Sub AddApplicationServices()
Scan(AddressOf SetupApplicationServices)
End Sub
Private Shared Sub SetupApplicationServices(ByVal y As IAssemblyScanner)
y.Assembly("DebtRemedy.ApplicationServices")
y.With(New FirstInterfaceConvention)
End Sub
End Class
Public Class FirstInterfaceConvention
Implements ITypeScanner
Public Sub Process(ByVal type As Type, ByVal graph As PluginGraph) Implements ITypeScanner.Process
If Not IsConcrete(type) Then
Exit Sub
End If
''//only works on concrete types
Dim firstinterface = type.GetInterfaces().FirstOrDefault()
''//grabs first interface
If firstinterface IsNot Nothing Then
graph.AddType(firstinterface, type)
Else
''//registers type
''//adds concrete types with no interfaces
graph.AddType(type)
End If
End Sub
End Class
I have tried both ForRequestedType (which I think is now deprecated) and For.
IRepository(Of T) lives in SharpArch.Core.PersistenceSupport.
Repository(Of T) lives in SharpArch.Data.NHibernate.
My servicelocator class
Public Class StructureMapServiceLocator
Inherits ServiceLocatorImplBase
Private container As IContainer
Public Sub New(ByVal container As IContainer)
Me.container = container
End Sub
Protected Overloads Overrides Function DoGetInstance(ByVal serviceType As Type, ByVal key As String) As Object
Return If(String.IsNullOrEmpty(key), container.GetInstance(serviceType), container.GetInstance(serviceType, key))
End Function
Protected Overloads Overrides Function DoGetAllInstances(ByVal serviceType As Type) As IEnumerable(Of Object)
Dim objList As New List(Of Object)
For Each obj As Object In container.GetAllInstances(serviceType)
objList.Add(obj)
Next
Return objList
End Function
End Class
My controllerfactory class
Public Class ServiceLocatorControllerFactory
Inherits DefaultControllerFactory
Protected Overloads Overrides Function GetControllerInstance(ByVal requestContext As RequestContext, ByVal controllerType As Type) As IController
If controllerType Is Nothing Then
Return Nothing
End If
Try
Return TryCast(ObjectFactory.GetInstance(controllerType), Controller)
Catch generatedExceptionName As StructureMapException
System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave())
Throw
End Try
End Function
End Class
The initialise stuff in my global.asax
Dim container As IContainer = New Container(New DefaultRegistry)
ControllerBuilder.Current.SetControllerFactory(New ServiceLocatorControllerFactory())
ServiceLocator.SetLocatorProvider(Function() New StructureMapServiceLocator(container))
My test controller
Public Class DataCaptureController
Inherits BaseController
Private ReadOnly clientRepository As IClientRepository()
Private ReadOnly pageRepository As IRepository(Of Page)
Public Sub New(ByVal clientRepository As IClientRepository(), ByVal pageRepository As IRepository(Of Page))
Check.Require(clientRepository IsNot Nothing, "clientRepository may not be null")
Check.Require(pageRepository IsNot Nothing, "pageRepository may not be null")
Me.clientRepository = clientRepository
Me.pageRepository = pageRepository
End Sub
Function Index() As ActionResult
Return View()
End Function
The above works fine when I take out everything to do with the pageRepository which is IRepository(Of T).
Any help with this would be greatly appreciated.
I had a similar issue yesterday with instantiating IRepository(Of MyEntity).
I had to state y.ConnectImplementationsToTypesClosing(GetType(IRepository(Of ))) in my Scan delegate to make StructureMap map generic types to their implementation.
Like this:
Private Shared Sub SetupCustomRepositories(ByVal y As IAssemblyScanner)
y.Assembly("DebtRemedy.Core")
y.Assembly("DebtRemedy.Data")
y.WithDefaultConventions()
y.ConnectImplementationsToTypesClosing(GetType(Of ));
End Sub
Make sure you are only creating one container.
I also converted a C# project from Castle Windsor to StructureMap. The original CW-based project instantiated a Container in Application_Start() (MVC2 project) and passed it around for configuration. I kept the same approach without thinking, kinda when you translate from Spanish to English litterally, and it's just as bad. :)
What happened is that I ended up creating a second SM container. StructureMap's container is static, and so there's always one "in the background". If you new up a container, you actually create a second, independent container. if you aren't careful, you end up sometimes using one, sometimes the other, and get a plague of " No Default Instance" errors at various points when you know it's defined..
The way I came across it is that I ended up littering my code with WhatDoIHave() calls, which was fortunate because I noted that sometimes I saw a configured container (the second) and sometimes I saw the static one (the first), which had not been configured. Different GUID names was the giveaway.
Check if the same is happening in your VB code.
Not that familiar with this, but it looks like it may not be registered with the container or because the resolver is greedy it might choose a constructor that does not have registered items. The following URL looks very similar to the same problem take a look...
http://learningbyfailing.com/2010/02/structuremap-exception-no-default-instance-defined-for-pluginfamily-iformsauthentication/

ASP.NET MVC tests with MSpec. Is this correct or needs refactoring?

I'm new to MSpec and would like to know if the way I wrote my test for ASP.NET MVC is correct. The test passes but I don't really like the way it's written and it seems awkward. I'm certainly missing something.
public class AccountControllerTests3
{
protected static AccountController controller;
static IFormsAuthenticationService formsService;
static IMembershipService membershipService;
protected static ActionResult result;
protected static LogOnModel model;
Establish context = () =>
{
var controllerBuilder = new TestControllerBuilder();
formsService = MockRepository.GenerateStub<IFormsAuthenticationService>();
membershipService = MockRepository.GenerateStub<IMembershipService>();
model = MockRepository.GenerateStub<LogOnModel>();
controller =
controllerBuilder.CreateController<AccountController>(new object[]
{
formsService,
membershipService
});
};
Because user_logs = () =>
{
bool rememberMe = false;
membershipService.Stub(
x => x.ValidateUser("bdd", "mspec")).Return(true);
formsService.Stub(x => x.SignIn("bdd", rememberMe));
controller.ModelState.IsValid.ShouldBeTrue();
};
}
[Subject(typeof(AccountController), "LogInTests")]
public class When_logging_into_application_with_good_login_and_password : AccountControllerTests3
{
private It user_should_be_redirected_to_the_home_page = () =>
{
model.UserName = "bdd";
model.Password = "mspec";
result = controller.LogOn(model, string.Empty);
result.AssertActionRedirect().ToAction<HomeController>(
x => x.Index());
};
}
[Subject(typeof(AccountController), "LogInTests")]
public class When_logging_into_application_with_bad_login_and_password : AccountControllerTests3
{
It The_error_message_should_be_shown = () =>
{
model.UserName = "BAD";
model.Password = "BAD";
result = controller.LogOn(model, string.Empty);
controller.ModelState[""].Errors[0].ErrorMessage.ShouldEqual(
"The user name or password provided is incorrect.");
};
}
Thanks in advance,
Thomas
One of my goals when I write tests with MSpec is to get the "Assert" or the "It" down to one line. MSpec is not like NUnit in that it only executes the Context (made up of the Establish clauses from the current class and all base classes and the Because clause) once followed by all of the Specifications (It clauses).
This is designed explicitly to force you to not perform any behavior in the It clauses, but rather observe it.
What you're actually doing here is using MSpec like NUnit. Try and rewrite the tests in a single class (using no inheritance). Work backwards... in the It, place a single line that asserts what you want to assert. Perhaps the AssertRedirect. In the Because, try and put a single line that causes the observations to be observable. This would probably be your call to the controller's logon method. Finally, in the "Establish context" you'd want to put everything else.
After a while, you may want to pull some of the things in the Establish context only into a base class, but in doing so, be sure that your entire subclass stands alone in terms of understanding. A reader shouldn't need to read the base class in order to understand what the actual spec is doing. It's ok to hide ceremonial implementation details, but be sure to hide them behind descriptive method names.
There's another line I'm not sure about:
controller.ModelState.IsValid.ShouldBeTrue();
If this is a test, it should probably be in its own It clause. Though really, do you want to test this? What are you testing here? Shouldn't your controller take an action based on whether or not the model is valid? Shouldn't the result of that action be observable (validation error instead of login error). I just wonder if you really need to test this.
A few other things to check out, first for styling with R#, it seems your tests are falling victim to R#'s defaults. I posted about how to fight this here:
http://codebetter.com/blogs/aaron.jensen/archive/2008/10/19/getting-resharper-and-vs-to-play-nice-with-mspec.aspx
Also, James Broome has some nice MVC MSpec extensions that are worth checking out:
http://jamesbroo.me/introducing-machinespecificationsmvc/
Good luck and Enjoy! Feel free to ping me on twitter if you have any other unrelated questions.
Here's a remark: instead of using CreateController method use InitializeController, because it is compile-time safer and refactor friendlier.
Instead of:
controller = controllerBuilder.CreateController<AccountController>(
new object[] { formsService, membershipService });
Do:
controller = new AccountController(formsService, membershipService);
controllerBuilder.InitializeController(controller);
The first will still compile if you change the controller constructor arguments and it will blow at runtime, while the second will generate a compile-time error.

How do i unit test this business logic?

i have a method that does takes in a object and saves it to the database. But, before i save the object, i do the following...
(psuedo code)
if (IsAuthenticated)
{
foo.UserId = AuthenticatedUser.Id;
}
else
{
foo.AnonEmail = "Jon#World-Domination";
foo.AnonName = "Jon Skeet";
}
try
{
_fooService.Save(foo);
}
catch
{
// Some view, with error stuff now added to
return View(...); ViewData.ModelState.
}
// all good, redirect to the proper next view.
return RedirectToAction(...);
That code works fine, but i'm not sure how to write the two unit tests for a success.
a) User is authenticated with valid data
b) User is not authentiated with valid data.
The reason why i'm not sure what to do is, is that both scenario return the same RedirectToAction(..) view object. So i can successfully test that .. but it doesn't tell me if the object saved contains the authenticated user id or the anon info. It's like i want the first unit test to say
moq up an authenticated user
call method
test if result is RedirectToActionView
test if the foo object that was persisted contains the moq'd user id.
thoughts?
Update
The common suggestion is that i mock the fooService. I'm currently using Dependency Injection and Moq, so could somone show me how i would use Moq? I'm not sure how the DI is important here, though ???
I would mock up the _fooService object, and test what it receives as part of your test. That way your surrounding code remains the same and is untouched, and by checking what _fooService receives, you can assert whether the behaviour is as expected. The return object is not of interest in this case.
How do you mock your _fooService ? You can either implement your own 'test' version (adhering to the same interface as the real world version), or using a mocking framework. Whichever approach you use, your code above needs to be configured with a given implementation of the _fooService (usually on construction - see dependency injection for more info on how this may work)
You might mock _fooService.Save(foo) and inspect the supplied foo.
Maybe you are finding it difficult to test the object because you have more than one activity taking place in a single method.
The overall theme here is controller logic.
Decorate the domain object with user information
Persist the update logic
Determine the next view to render based on success/failure
If you extract another object (IUserDecoratorService) then your code looks like
userService.UpdateUserInformation(foo);
try
{
_fooService.Save(foo);
}
catch
{
// Some view, with error stuff now added to
return View(...); ViewData.ModelState.
}
// all good, redirect to the proper next view.
return RedirectToAction(...);
This method is simple to test as it is 2 simple interactions with the 2 services and a routing decision which you can already test.
Now you just need to write the tests for your new service:
[Test]
public void ShouldDecorateWithUserIdForAuthenticatedUser()
{
{setup authenticated user}
:
service.UpdateUserInformation(foo);
Assert.AreEqual(expectedId, foo.UserId);
Assert.IsNull(foo.AnonEmail);
Assert.IsNull(foo.AnonEName);
}
[Test]
public void ShouldSpoofTheAllKnowingSkeetIfAnonymousUser()
{
{setup anonymous user}
:
service.UpdateUserInformation(foo);
Assert.AreEqual(UnassignedId, foo.UserId);
Assert.AreEqual("Jon#World-Domination", foo.AnonEmail);
Assert.AreEqual("Jon Skeet", foo.AnonName);
}
you still have a reference to your object. At the end of your unit test, couldn't you just assert what the value was foo.AnonEmail or UserId?
Unit tests should not touch an external source, (that's an integration test) so if you go that route you should mock your datasource and then test through your mock.
Do you have access to foo in the test? I'm assuming it's a field on the class. Is there a public getter? If not you may have to use Reflection (I assume that's available in asp.net, but I'm not too familiar with it)
You want to use the DI to get the correct implementation of fooservice into your object, so at testing time you can do this;
(Using Moq)
[TestMethod]
public void Jon_Skeet_Is_Saved_If_User_Not_Authenticated()
{
bool jonWasSaved = false;
var mockFooService = new Mock<IFooService>();
mockFooService
.Expect(x => x.Save(It.Is<Foo>(foo => foo.AnonName == "Jon Skeet")))
.Callback(() => jonWasSaved = true;);
FooManager instance = new FooManager(mockFooService.Object);
Foo testFoo = new Foo();
testFoo.UserId = 1; // this is not the authenticated id
instance.baa(foo);
Assert.IsTrue(jonWasSaved);
}
You may also want to pass in a mock version of whatever service you use to check the AuthetnicatedUser.Id
HTH

Resources