微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐