asp.net MVC ModelState 在我的单元测试中为 null。为什么?
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(),我不会得到 null:
public class TestController : Controller
{
public ViewResult Index()
{
return new ViewResult();
}
}
但是... IsValid() 在不应该返回 true 的情况下返回 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
}
}
我认为我在这里做了一些根本错误的事情,但我不知道是什么。有人能指出我正确的方向吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您检查这一点,达林。
我安装了 MVC 1 RC 和 MVC 2 RC 2 版本。我卸载了它们,安装了 MVC 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.