我有 mvc 应用程序,我正在使用 poco 对象并编写单元测试。问题是,当我的所有测试到达这行代码 Roles.IsUserInRole("someUser", "role") 时,它们都会失败。我应该为角色实现新的接口(interface)或存储库还是......? 谢谢
最佳答案
当我尝试在编码的单元测试中模拟 Roles.IsUserInRole 功能时,我遇到了同样的问题。我的解决方案是创建一个名为 RoleProvider 的新类和一个带有方法 IsUserInRole 的接口(interface),然后调用 System.Web.Security.Roles.IsUserInRole:
public class RoleProvider: IRoleProvider
{
public bool IsUserInRole(IPrincipal userPrincipal)
{
return System.Web.Security.Roles.IsUserInRole(userPrincipal.Identity.Name, "User");
}
}
然后在我的代码中我调用 RoleProvider IsUserInRole 方法。由于您有一个接口(interface),因此您可以在测试中模拟 IRoleProvider,此处显示的示例是使用 Rhino Mocks:
var roleProvider = MockRepository.GenerateStub<IRoleProvider>();
roleProvider.Expect(rp => rp.IsUserInRole(userPrincipal)).Return(true);
希望这有帮助。
关于asp.net-mvc - 单元测试(mvc) - 角色问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4595090/