我如何单元测试MVC重定向?
public ActionResult Create(Product product) { _productTask.Save(product); return RedirectToAction("Success"); } public ActionResult Success() { return View(); }
是Ayende的做法仍然是最好的方式,与预览5:
public static void RenderView(this Controller self, string action) { typeof(Controller).GetMethod("RenderView").Invoke(self,new object[] { action} ); }
似乎很奇怪必须这样做,特别是当MVC团队已经表示他们正在编写可测试的框架时.
[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"); } }