如何对使用 FormsAuthentication 的 ASP.NET MVC 控制器进行单元测试? [英] How can I unit test my ASP.NET MVC controller that uses FormsAuthentication?
问题描述
我正在以测试驱动的方式使用 ASP.NET MVC 解决方案,我想使用表单身份验证将用户登录到我的应用程序.我希望在控制器中最终得到的代码如下所示:
I'm working with a ASP.NET MVC solution in a test driven manner and I want to login a user to my application using forms authentication. The code I would like to end up with in the controller looks something like this:
FormsAuthentication.SetAuthCookie(userName, false);
我的问题是如何编写测试来证明这段代码的合理性?
My question is how do I write a test to justify this code?
有没有办法检查是否使用正确的参数调用了 SetAuthCookie 方法?
Is there a way to check that the SetAuthCookie method was called with the correct parameters?
有没有办法注入一个假的/模拟的 FormsAuthentication?
Is there any way of injecting a fake/mock FormsAuthentication?
推荐答案
我会先写一个接口和一个封装这个逻辑的包装类,然后在我的控制器中使用这个接口:
I would start by writing an interface and a wrapper class that will encapsulate this logic and then use the interface in my controller:
public interface IAuth
{
void DoAuth(string userName, bool remember);
}
public class FormsAuthWrapper : IAuth
{
public void DoAuth(string userName, bool remember)
{
FormsAuthentication.SetAuthCookie(userName, remember);
}
}
public class MyController : Controller
{
private readonly IAuth _auth;
public MyController(IAuth auth)
{
_auth = auth;
}
}
现在 IAuth
可以在单元测试中轻松模拟,并验证控制器是否调用了预期的方法.我不会对 FormsAuthWrapper
类进行单元测试,因为它只是将调用委托给 FormsAuthentication
执行它应该做的事情(微软保证:-)).
Now IAuth
could be easily mocked in a unit test and verify that the controller calls the expected methods on it. I would NOT unit test the FormsAuthWrapper
class because it just delegates the call to the FormsAuthentication
which does what it is supposed to do (Microsoft guarantee :-)).
这篇关于如何对使用 FormsAuthentication 的 ASP.NET MVC 控制器进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!