我有一个方法canUserRead,它可以作为用户处理null参数(因为有时候用户没有登录)。
现在我想创建一个存根,其行为反映了该方法的行为。我试过了:
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变量没有帮助。
那么,如何创建一个stub方法,在传递null参数时返回合理的东西?
答案 0 :(得分: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);
答案 1 :(得分: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);
答案 2 :(得分: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);