Reputation: 1737
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?
Upvotes: 1
Views: 1608
Reputation: 6683
I'd suggest Arg<T>.Is.Null
:
stubAccessRights
.Stub(ar => ar.canUserRead(Arg<IUser>.Is.Null, confidentialDocument))
.Return(false);
stubAccessRights
.Stub(ar => ar.canUserRead(Arg<IUser>.Is.Null, nonConfidentialDocument))
.Return(true);
Upvotes: 4
Reputation: 8355
I think you can use the Arg<T>.Is.Anything
syntax
IAccessRightsManager stubAccessRights = new
MockRepository.GenerateStub<IAccessRightsManager>();
stubAccessRights.Stub(ar => ar.canUserRead(Arg<IUser>.Is.Anything, confidentialDocument))
.Return(false);
stubAccessRights.Stub(ar => ar.canUserRead(Arg<IUser>.Is.Anything, nonConfidentialDocument))
.Return(true);
Upvotes: 1
Reputation: 2127
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);
Upvotes: 2