单元测试(mvc) - 角色问题
我有 mvc 应用程序,正在使用 poco 对象并编写单元测试。问题是,当我的所有测试到达这行代码 Roles.IsUserInRole("someUser", "role") 时,它们都会失败。我应该为角色实现新的接口或存储库还是......? 谢谢
I have mvc application and I'm working with poco objects and writing unit test. Problem is that all my test fail when they reach this line of code Roles.IsUserInRole("someUser", "role"). Should I implement new interface or repository for Roles or...?
Thx
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当我尝试在编码的单元测试中模拟 Roles.IsUserInRole 功能时,我遇到了同样的问题。我的解决方案是创建一个名为 RoleProvider 的新类和一个带有方法 IsUserInRole 的接口,然后调用 System.Web.Security.Roles.IsUserInRole:
然后在我的代码中我调用 RoleProvider IsUserInRole 方法。由于您有一个接口,因此您可以在测试中模拟 IRoleProvider,这里显示的示例是使用 Rhino Mocks:
希望这会有所帮助。
I had the same problem when trying to mock the Roles.IsUserInRole functionality in my coded unit tests. My solution was to create a new class called RoleProvider and an interface with method IsUserInRole which then called the System.Web.Security.Roles.IsUserInRole:
Then in my code I call the RoleProvider IsUserInRole method. As you have an interface you can then mock the IRoleProvider in your tests, example shown here is using Rhino Mocks:
Hope this helps.
您可以设置自定义方法来检查在测试中表现不同的角色,但我更喜欢让测试设置一个可与标准方法一起使用的上下文。
http ://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx
You can set up a custom method to check roles that will behave differently in tests, but I prefer to have the tests set up a context that will work with the standard methods.
http://stephenwalther.com/blog/archive/2008/07/01/asp-net-mvc-tip-12-faking-the-controller-context.aspx
您可以使用谓词/函数创建一个轻量级包装器。
然后使用 IsUserInRole() 而不是 Roles.IsUserInRole()。在运行时你会得到相同的行为。但在测试时,您可以覆盖该函数,以便它不会访问 RoleProvider
如果您不想使用公共静态,您可以通过构造函数注入谓词并将其存储为私有只读。
如果您使用 Moq,您可以返回一个模拟,然后控制返回值和/或检查调用的方法。并检查发送到谓词的参数值。
You could create a light wrapper with a Predicate/Func.
Then use IsUserInRole() instead of Roles.IsUserInRole(). At run time you get the same behavior. But at test time you can override the function so that it doesn't access the RoleProvider
If you prefer to not have a public static you could inject the Predicate via your constructor and store it as a private readonly.
If you use Moq you can return a mock and then control the return value and/or check the method was called. And check what parameter value was sent to the Predicate.