2010-03-04 215 views
0

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

我想我在這裏做了一些根本性的錯誤,我不知道是什麼。任何人都可以將我指向正確的方向嗎?

+0

我剛剛運行了你的第一個測試(你說它失敗了),它運行得很好。所以也許還有別的。 – 2010-03-05 08:02:24

回答

0

感謝您檢查Darin。

我安裝了MVC 1 RC和MVC 2 RC 2版本。我卸載了他們兩個,安裝了MVC 1,現在一切都按預期行事。測試不會失敗。

+0

有趣。我有與ASP.NET MVC 4相同的問題 – SiberianGuy 2012-10-07 06:44:34

相關問題