1

我有一个方法,canUserRead,它可以作为用户处理空参数(因为有时用户没有登录)。

现在我想创建一个其行为反映该方法的存根。我试过:

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

这不会编译,因为 null 不是 IUser 类型。而且 null 没有引用标识,因此用 null 初始化一个新的 IUser 变量没有帮助。

那么,如何创建一个存根方法,该方法在传递一个空参数时返回一些合理的东西?

4

3 回答 3

4

我建议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);
于 2013-10-22T12:09:17.763 回答
2

试试这个:

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); 
于 2013-10-22T11:17:35.113 回答
1

我认为您可以使用Arg<T>.Is.Anything语法

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); 
于 2013-10-22T11:20:44.813 回答