使用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");

试试这个。。。

var result = sut.Create(newProduct) as RedirectToRouteResult;
Assert.Equal(result.RouteValues["action"], "Index");

如果你在重定向中传递一个参数,你可以这样做。。。

var result = sut.Create(newProduct) as RedirectToRouteResult;
Assert.Equal(result.RouteValues["action"], "Index");
Assert.Equal(result.RouteValues["Parameter Name"], "Parameter Value");

希望这有帮助:)

最新更新