I have a method, canUserRead, which can handle a null argument as the user (because sometimes users are not logged in).
Now I want to create a stub whose behavior reflects that of the method. I tried:
IAccessRightsManager stubAccessRights = new
MockRepository.GenerateStub<IAccessRightsManager>();
// if there is no user logged in
stubAccessRights.Stub(ar => ar.canUserRead(null, confidentialDocument))
.Return(false); //doesn't compile
stubAccessRights.Stub(ar => ar.canUserRead(null, nonConfidentialDocument))
.Return(true); //doesn't compile
// if there is a user without confidentiality clearance logged in
stubAccessRights.Stub(ar => ar.canUserRead(nonPrivilegedUser, confidentialDocument))
.Return(false);
stubAccessRights.Stub(ar => ar.canUserRead(nonPrivilegedUser, nonConfidentialDocument))
.Return(true);
// if there is a user with confidentiality clearance logged in
stubAccessRights.Stub(ar => ar.canUserRead(privilegedUser, confidentialDocument))
.Return(true);
stubAccessRights.Stub(ar => ar.canUserRead(privilegedUser, nonConfidentialDocument))
.Return(true);
This does not compile, because null is not of type IUser. And null doesn't have referential identity, so initializing a new IUser variable with null doesn't help.
So, how do I create a stub method which returns something sensible when passed a null argument?
Try this:
IAccessRightsManager stubAccessRights = new
MockRepository.GenerateStub<IAccessRightsManager>();
stubAccessRights.Stub(ar => ar.canUserRead((IUser)null, confidentialDocument))
.Return(false);
stubAccessRights.Stub(ar => ar.canUserRead((IUser)null, nonConfidentialDocument))
.Return(true);