【问题标题】:Unit testing ASP.NET MVC redirection单元测试 ASP.NET MVC 重定向
【发布时间】:2010-09-08 16:20:24
【问题描述】:

如何对 MVC 重定向进行单元测试?

public ActionResult Create(Product product)
{
    _productTask.Save(product);
    return RedirectToAction("Success");   
}

public ActionResult Success()
{ 
     return View();
}

Ayende's 方法仍然是最好的方法吗,预览 5:

 public static void RenderView(this Controller self, string action) 
 {
    typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); 
 }

必须这样做似乎很奇怪,尤其是 MVC 团队说他们正在编写可测试的框架。

【问题讨论】:

    标签: asp.net asp.net-mvc unit-testing


    【解决方案1】:
    [TestFixture]
    public class RedirectTester
    {
        [Test]
        public void Should_redirect_to_success_action()
        {
            var controller = new RedirectController();
            var result = controller.Index() as RedirectToRouteResult;
            Assert.That(result, Is.Not.Null);
            Assert.That(result.Values["action"], Is.EqualTo("success"));
        }
    }
    
    public class RedirectController : Controller
    {
        public ActionResult Index()
        {
            return RedirectToAction("success");
        }
    }
    

    【讨论】:

    • RedirectToRouteResult.Values[] 现在是 RedirectToRouteResult.RouteValues[...]
    • 有谁知道在测试期间重定向时如何实际调用该操作?
    • @f0ster 你为什么想要那个?无论哪种方式,以上示例中的controller.Success() 都会完成此操作。
    【解决方案2】:

    这适用于使用 NUnit 的 ASP.NET MVC 5:

        [Test]
        public void ShouldRedirectToSuccessAction()
        {
            var controller = new RedirectController();
            var result = controller.Index() as RedirectToRouteResult;
    
            Assert.That(result.RouteValues["action"], Is.EqualTo("success"));
        }
    

    如果你想测试你正在重定向到不同的控制器(比如 NewController),断言应该是:

    Assert.That(result.RouteValues["controller"], Is.EqualTo("New"));
    

    【讨论】:

      【解决方案3】:

      您可以对返回的 ActionResult 进行断言,您需要将其转换为适当的类型,但它确实允许您使用基于状态的测试。在 Web 上搜索应该会找到一些有用的链接,不过这里是 just one。

      【讨论】:

        【解决方案4】:

        您可以使用 Mvc.Contrib.TestHelper,它为测试重定向提供断言。查看http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html 和代码示例。这可能会有所帮助。

        【讨论】:

        • 根据FAQ "Be careful, because the community frowns on overt self-promotion and tends to vote it down and flag it as spam. Post good, relevant answers, and if they happen to be about your product or website, so be it. However, you must disclose your affiliation in your answers. Also, if a huge percentage of your posts include a mention of your product or website, you're probably here for the wrong reasons."
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-12
        • 1970-01-01
        • 1970-01-01
        • 2010-10-14
        • 1970-01-01
        相关资源
        最近更新 更多