How to unit-test an action, when return type is ActionResult?

前端 未结 3 1916
抹茶落季
抹茶落季 2020-12-05 09:44

I have written unit test for following action.

[HttpPost]
public ActionResult/*ViewResult*/ Create(MyViewModel vm)
{
    if (ModelState.IsValid)
    {
               


        
相关标签:
3条回答
  • 2020-12-05 10:12

    Try this code:

    dynamic result=objectController.Index();
    Assert.AreEqual("Index",result.ViewName);
    
    0 讨论(0)
  • 2020-12-05 10:15

    Please note that

    Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult)); 
    

    has been deprecated.

    The new syntax is

    Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
    
    0 讨论(0)
  • 2020-12-05 10:17

    So here is my little example:

    public ActionResult Index(int id)
    {
      if (1 != id)
      {
        return RedirectToAction("asd");
      }
      return View();
    }
    

    And the tests:

    [TestMethod]
    public void TestMethod1()
    {
      HomeController homeController = new HomeController();
      ActionResult result = homeController.Index(10);
      Assert.IsInstanceOfType(result,typeof(RedirectToRouteResult));
      RedirectToRouteResult routeResult = result as RedirectToRouteResult;
      Assert.AreEqual(routeResult.RouteValues["action"], "asd");
    }
    
    [TestMethod]
    public void TestMethod2()
    {
      HomeController homeController = new HomeController();
      ActionResult result = homeController.Index(1);
      Assert.IsInstanceOfType(result, typeof(ViewResult));
    }
    

    Edit:
    Once you verified that the result type is ViewResut you can cast to it:

    ViewResult vResult = result as ViewResult;
    if(vResult != null)
    {
      Assert.IsInstanceOfType(vResult.Model, typeof(YourModelType));
      YourModelType model = vResult.Model as YourModelType;
      if(model != null)
      {
        //...
      }
    }
    
    0 讨论(0)
提交回复
热议问题