【问题标题】:asp.net MVC ModelState is null in my Unit Test. Why?asp.net MVC ModelState 在我的单元测试中为空。为什么?
【发布时间】:2011-01-23 19:09:53
【问题描述】:

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:

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
    }
}

我认为我在这里做错了什么,我不知道是什么。谁能指出我正确的方向?

【问题讨论】:

  • 我刚刚运行了你的第一个测试(你说它失败的那个),它运行得非常好。所以也许还有别的东西。

标签: asp.net-mvc null unit-testing modelstate


【解决方案1】:

感谢您的检查,达林。

我安装了 MVC 1 RC 和 MVC 2 RC 2 版本。我卸载了它们,安装了 MVC 1,现在一切都按预期运行。测试没有失败。

【讨论】:

  • 有趣。我对 ASP.NET MVC 4 有同样的问题
猜你喜欢
  • 1970-01-01
  • 2011-11-07
  • 2020-10-22
  • 2012-07-06
  • 2011-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-02
相关资源
最近更新 更多