如何在 ASP.NET MVC 中模拟 Membership 类以启用测试
我正在构建一个允许用户注册的 ASP.NET MVC 3 站点。为此,我使用内置的(静态)Membership
类;有人说它臃肿,但它工作得很好而且很容易,所以你就可以了。
不管怎样,我已经开始编写 AdminService 类来处理用户帐户相关的功能,并且让我们假设这个问题只有一种方法:
public class AdminService : IAdminService
{
public void DeleteUser(string username)
{
Membership.DeleteUser(username);
}
}
使用像这样的 Membership 类有两种错误:它不能通过 IoC 注入,并且我我发现为 IAdminService
编写规范(测试)越来越困难,因为我无法模拟 Membership 类。
有没有一种方法可以使 ASP.NET 会员类测试友好且依赖注入友好,而无需自己动手?
就功能而言,Membership 类运行良好,更重要的是,它 现在可以工作了,所以我真的不愿意开始编写自己的 MembershipProvider,因为它只会减慢我的速度。
I'm building an ASP.NET MVC 3 site that allows users to register. To that end I'm using the built in (static) Membership
class; some say it is bloated but it works well and easily enough so there your are.
Anyway, I've started writing and AdminService class which will handle user account related functionality, and let's assume for the question that it has only one method:
public class AdminService : IAdminService
{
public void DeleteUser(string username)
{
Membership.DeleteUser(username);
}
}
Using the Membership class like this wrong in 2 ways: it cannot be injected via IoC and I'm finding it increasingly hard to write specs (test) for IAdminService
because I cannot mock the Membership class.
Is there a way to make the ASP.NET Membership class test-friendly and Dependency injection friendly without rolling my own?
When it comes to functionality, the Membership class works well and, more importantly, it
works now, so I'm really reluctant to start writing my own MembershipProvider as it would only slow me down.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您创建非空 ASP.NET MVC 3 项目,您的 Models 文件夹中将会有 AccountModels.cs 文件。它包含一个如何处理成员资格以启用单元测试的示例:
If you create non-empty ASP.NET MVC 3 project there will be AccountModels.cs file in your Models folder. It contains a sample how to deal with membership to enable unit-testing:
当我构建 MVC 站点时也遇到了同样的情况,并最终推出了我自己的(可测试的)提供程序。
话虽这么说,一种选择是从此处 - 你可以(理论上)只构建一个 FakeProvider,并对各种返回方法进行硬编码,而不是访问 SQL 数据库。
其中一个方法的总数相当少,当你想伪造这些方法时,拥有它并不是一件坏事。
Had this same situation when I was building out an MVC site, and ended up rolling my own (testable) provider.
That being said, one option would be to just lift the sample implementation from here - you could (in theory) just build a FakeProvider, and hard-code the various return methods vs. hit a SQL database.
The total number of methods in one of these is pretty light, and would not be a bad thing to have around for when you want to fake these out.