ModelState 在我的单元测试中总是返回 null。我希望有人能告诉我为什么。
给定以下控制器:
public class TestController : Controller
{
public ViewResult Index()
{
return View();
}
}
通过此测试,我的 ModelState 测试为 null:
public void ModelState_Is_Not_Null()
{
TestController controller = new TestController();
var result = controller.Index();
// This test is failing:
Assert.IsNotNull(controller.ViewData.ModelState);
}
如果我更改控制器以返回一个新的 ViewResult() 我不会得到空值:
public class TestController : Controller
{
public ViewResult Index()
{
return new ViewResult();
}
}
但是......如果我这样做,IsValid() 在不应该的时候返回 true:
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
}
}
我认为我在这里做的事情根本上是错误的,我不知道是什么。谁能指出我正确的方向?