testingrhino-mockspartial-mocks

Expectations on Partial Mock - NullReference Exception


I've a problem with partial mocking using Rhino Mocks:

var authentication = (FormsAuthenticationService)_mocks.PartialMock(
  typeof(FormsAuthenticationService));
Expect.Call( delegate{ authentication.SetAuthCookie(null, null); }).IgnoreArguments();

..and I get NullReferenceException on "Expect." line..

I will just add that FormsAuthenticationService implements IAuthentication


Solution

  • Is there a good reason you're trying to mock the physical class, rather than the interface? I ask this because there are 2 potential problems with mocking FormsAuthenticationService:

    1. The class may not have a default parameterless constructor (in which case, you need to specify an overloaded method of mocks.PartialMock).

    2. The SetAuthCookie has to be virtual. Mock frameworks typically can mock only non-sealed classes, and only the virtual members of such a class.

    To get around these problems, I'd recommend mocking IAuthentication instead. Mocking interfaces doesn't have these limitations. Here's the code you'd write:

    var authentication = _mocks.DynamicMock<IAuthentication>();
    Expect.Call(() => authentication.SetAuthCookie(null, null)).IgnoreArguments();