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

在单元测试中是否有一种简单的方法来验证控制器动作确实重定向到特定页面

控制器代码

public ActionResult Create(ProductModel newProduct)
{
    this.repository.CreateProduct(newProduct);
    return RedirectToAction("Index");
}

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

ProductController controller = new ProductController(repository);

RedirectToRouteResult result = (RedirectToRouteResult)controller.Create(newProduct);

bool redirected = checkGoesHere;
Assert.True(redirected,"Should have redirected to 'Index'");

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

解决方法

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

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

// arrange
var sut = new ProductController(repository);

// act
var result = sut.Create(newProduct);

// assert
result
    .AssertActionRedirect()
    .ToAction("Index");

相关文章

ASP.NET与IIS是紧密联系的,由于IIS6.0与IIS7.0的工作方式的...
在之前的ASP.NET是如何在IIS下工作的这篇文章中介绍了ASP.NE...
这篇文章主要讲解了“WPF如何实现带筛选功能的DataGrid”,文...
本篇内容介绍了“基于WPF如何实现3D画廊动画效果”的有关知识...
Some samples are below for ASP.Net web form controls:(fr...
问题描述: 对于未定义为 System.String 的列,唯一有效的值...