asp.net MVC ModelState is null in my Unit Test. Why?

帅比萌擦擦* 提交于 2019-12-13 03:49:11

问题


ModelState is always returning null in my unit tests. I was hoping someone could tell me why.

Given the following controller:

public class TestController : Controller
{
   public ViewResult Index()
    {
        return View();
    }
}

My test gets null for ModelState with this test:

public void ModelState_Is_Not_Null()
{
    TestController controller = new TestController();
    var result = controller.Index();

    // This test is failing:
    Assert.IsNotNull(controller.ViewData.ModelState);
}

If I change the controller to return a new ViewResult() I don't get null:

public class TestController : Controller
{
  public ViewResult Index()
  {
    return new ViewResult();
  }
}

But... IsValid() returns true when it shouldn't if I do it this way:

public class TestController : Controller
{
   public ViewResult Index()
    {
        ModelState.AddModelError("Test", "This is an error");
        return new ViewResult();

        // I don't get null in the test for ModelState anymore, but IsValid()
        // returns true when it shouldn't
    }
}

I think I'm doing something fundamentally wrong here and I don't know what. Could anyone point me in the right direction?


回答1:


Thanks for checking that, Darin.

I had the MVC 1 RC and MVC 2 RC 2 versions installed. I uninstalled both of them, installed MVC 1 and now everything is behaving as expected. The test doesn't fail.



来源:https://stackoverflow.com/questions/2381448/asp-net-mvc-modelstate-is-null-in-my-unit-test-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!