【发布时间】:2012-07-09 13:15:07
【问题描述】:
您好,我正在对我的 ASP.Net MVC2 项目进行一些单元测试。我正在使用 Moq 框架。在我的 LogOnController 中,
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl = "")
{
FormsAuthenticationService FormsService = new FormsAuthenticationService();
FormsService.SignIn(model.UserName, model.RememberMe);
}
在 FormAuthenticationService 类中,
public class FormsAuthenticationService : IFormsAuthenticationService
{
public virtual void SignIn(string userName, bool createPersistentCookie)
{
if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName");
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
我的问题是如何避免执行
FormsService.SignIn(model.UserName, model.RememberMe);
这一行。或者有什么办法可以起订量
FormsService.SignIn(model.UserName, model.RememberMe);
使用 Moq 框架不更改我的 ASP.Net MVC2 项目。
【问题讨论】:
-
什么是 SUT(被测系统) -
LogOnController或FormsAuthenticationService?如果是前者,则应该为FormsAuthenticationService提供一个假的,并且您应该验证它是否调用了SignIn方法。后者更难进行单元测试,因为它需要一个当前的HttpContext来添加一个cookie(到HttpResponse)。 -
我想测试 LogOnController。我试图模拟 FormsService.SignIn(model.UserName, model.RememberMe);这样, var formService=new Mock
();但是 formservice.SignIn 不返回任何内容。如何避免执行该行或如何模拟该行。我不知道如何使用 Moq 来模拟它。
标签: c# unit-testing asp.net-mvc-2 moq