1

好的 - 所以我是这样开始的,

public ViewResult Index()
{
   return View(service.GetProjects());
}

这是我的测试。

[TestMethod]
public void Index_Will_Return_A_List_Of_Active_Projects()
{
   var view = controller.Index();
   Assert.AreEqual(view.ViewData.Model.GetType(), typeof(List<Project>));
}

所有这一切都被 dokken 所震撼,但后来我添加了登录名,如果用户未通过身份验证,我将他们重定向到登录页面。这是新方法的样子。

   public ActionResult Index()
   {
      if (Request.IsAuthenticated)
          return View(service.GetProjects());
      return RedirectToAction("Login", "Account");
   }

我的问题是这个 - 我无法弄清楚如何为我的生活修复单元测试。我无法再返回 ViewResult,因此无法检查 .ViewData.Model 属性,但我无法弄清楚如何在返回查看结果的同时重定向。我一直在浏览该网站,发现这个如何在 ViewResult 或 ActionResult 函数中重定向?但这并没有真正的帮助。

如果有人能告诉我这将是什么规则 - 我很难过。

4

2 回答 2

1

您的测试将不得不添加另一个步骤:断言返回的是一个ViewResult. 如果该断言成功,则将其强制转换,并继续使用另一个断言。

[TestMethod]
public void Index_Will_Return_A_List_Of_Active_Projects()
{
   var result = controller.Index();
   // this is called a guard assertion
   Assert.IsInstanceOfType(result, typeof(ViewResult)); 

   var view = (ViewResult)result;
   Assert.AreEqual(view.ViewData.Model.GetType(), typeof(List<Project>));
}
于 2012-07-12T03:51:57.127 回答
1

我会从您的操作中删除该逻辑并改用AuthorizeAttribute。然后您的测试不会改变,您可以创建一个单独的测试,断言该操作正在被属性修饰。

[Authorize]
public ViewResult Index() 
{ 
    return View(service.GetProjects()); 
}
于 2012-07-12T03:59:48.347 回答