Question

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?

Était-ce utile?

La solution 2

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); 

Autres conseils

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);

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); 
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top