Unit testing ASP.NET MVC redirection

前端 未结 4 1871
南笙
南笙 2021-02-05 09:50

How do I Unit Test a MVC redirection?

public ActionResult Create(Product product)
{
    _productTask.Save(product);
    return RedirectToAction(\"Success\");   
         


        
相关标签:
4条回答
  • 2021-02-05 10:36

    You can assert on the ActionResult that is returned, you'll need to cast it to the appropriate type but it does allow you to use state-based testing. A search on the Web should find some useful links, here's just one though.

    0 讨论(0)
  • 2021-02-05 10:43
    [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");
        }
    }
    
    0 讨论(0)
  • 2021-02-05 10:44

    you can use Mvc.Contrib.TestHelper which provides assertions for testing redirections. Take a look at http://kbochevski.blogspot.com/2010/06/unit-testing-mvcnet.html and the code sample. It might be helpful.

    0 讨论(0)
  • 2021-02-05 10:48

    This works for ASP.NET MVC 5 using NUnit:

        [Test]
        public void ShouldRedirectToSuccessAction()
        {
            var controller = new RedirectController();
            var result = controller.Index() as RedirectToRouteResult;
    
            Assert.That(result.RouteValues["action"], Is.EqualTo("success"));
        }
    

    If you want to test that you are redirecting to a different controller (say NewController), the assertion would be:

    Assert.That(result.RouteValues["controller"], Is.EqualTo("New"));
    
    0 讨论(0)
提交回复
热议问题