asp.net-mvc – 使用单元测试在asp.net mvc中验证重定向

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 使用单元测试在asp.net mvc中验证重定向前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在单元测试中是否有一种简单的方法来验证控制器动作确实重定向到特定页面

控制器代码

  1. public ActionResult Create(ProductModel newProduct)
  2. {
  3. this.repository.CreateProduct(newProduct);
  4. return RedirectToAction("Index");
  5. }

所以在我的测试中,我需要验证控制器实际上是重定向.

  1. ProductController controller = new ProductController(repository);
  2.  
  3. RedirectToRouteResult result = (RedirectToRouteResult)controller.Create(newProduct);
  4.  
  5. bool redirected = checkGoesHere;
  6. Assert.True(redirected,"Should have redirected to 'Index'");

我只是不知道如何做验证.有任何想法吗?

解决方法

当然:
  1. Assert.AreEqual("Index",result.RouteValues["action"]);
  2. Assert.IsNull(result.RouteValues["controller"]); // means we redirected to the same controller

并使用MvcContrib.TestHelper,您可以以更优雅的方式编写本机测试(您甚至不需要投射到RedirectToRouteResult):

  1. // arrange
  2. var sut = new ProductController(repository);
  3.  
  4. // act
  5. var result = sut.Create(newProduct);
  6.  
  7. // assert
  8. result
  9. .AssertActionRedirect()
  10. .ToAction("Index");

猜你在找的asp.Net相关文章