Wednesday, February 25, 2009

NullReferenceException when using Rhino Mocks

While writing some tests for the following method I had a strange problem. When the test ran it threw a NullReferenceExceptions for my stubbed User object.

The method under test is simple enough

public void SetCookie(IHttpContextService context)
{
if (context == null)
return;
if (context.User == null)
return;
if (context.User.Identity == null)
return;
if (!context.User.Identity.IsAuthenticated)
return;
this.UserName = context.User.Identity.Name;
// Create a cookie for username and key
var cookie = new HttpCookie("Token", this.UserNameOnly + "|" + GetKey(this.Input));
context.CookieCollection.Add(cookie);
}
view raw example1.cs hosted with ❤ by GitHub

as is the test case

[Test]
public void Should_SetACookie()
{
var httpContextService = MockRepository.GenerateStub<IHttpContextService>();
var cookieCollection = new HttpCookieCollection();
IPrincipal user = new GenericPrincipal(new GenericIdentity("Test"),
new[] {"TestRole"});
httpContextService.Stub(c => c.User).Return(user);
httpContextService.Stub(c => c.CookieCollection).Return(cookieCollection);
cookieSetter.SetCookie(httpContextService);
httpContextService.VerifyAllExpectations();
}
view raw example2.cs hosted with ❤ by GitHub

The mocking Framework is Rhino Mocks and this was the solution to the problem.

With Rhino a call to a stub (or mock) is expected only once while my method is checking the user object a number of times. Eventually the test will just check that the cookie has been set so I can change the User stub to:

httpContextService.Stub(c => c.User).Return(user).Repeat.Any();
view raw example3.cs hosted with ❤ by GitHub

No comments: