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?