ModelState在我的單元測試中總是返回null。我希望有人能告訴我爲什麼。asp.net MVC ModelState在我的單元測試中爲null。爲什麼?
鑑於以下控制器:
public class TestController : Controller
{
public ViewResult Index()
{
return View();
}
}
我的測試得到空值的ModelState與這個測試:
public void ModelState_Is_Not_Null()
{
TestController controller = new TestController();
var result = controller.Index();
// This test is failing:
Assert.IsNotNull(controller.ViewData.ModelState);
}
如果我改變控制器返回一個新的ViewResult()我不明白null:
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
}
}
我想我在這裏做了一些根本性的錯誤,我不知道是什麼。任何人都可以將我指向正確的方向嗎?
我剛剛運行了你的第一個測試(你說它失敗了),它運行得很好。所以也許還有別的。 – 2010-03-05 08:02:24