在Asp.Net MVC网页API ModelState.IsValid总是正确的测试控制器的时候, [英] ModelState.IsValid always true when testing Controller in Asp.Net MVC Web Api
问题描述
我试图使这一工作,提出了许多谷歌/计算器搜索,没有运气可言。
I have tried to make this works and made many google/stackoverflow searches with no luck at all.
我有一个简单的模型:
public class MovieModel
{
public string Id { get; set; }
[Required]
[StringLength(100)]
public string Name { get; set; }
}
在控制器的方法:
// POST: api/Movies
public IHttpActionResult Post([FromBody]MovieModel movieModel)
{
if (ModelState.IsValid)
{
//Code
}
}
和测试方法(是一个集成测试,但同样会在单元测试发生):
And a test method (is an integration test, but the same would happen in unit tests):
[TestMethod]
public void MoviesController_Post_Without_Name()
{
// Arrange
var model = new MovieModel();
model.Name = "";
// Act
var result = controller.Post(model);
// Assert
Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
Assert.AreEqual(6, controller.Get().Count());
}
尽管该模式显然是无效的,它总是IsValid属性计算为true。
Despite the fact that the model is clearly invalid it always evaluate the IsValid property to true.
我试过很多方法至今没有成功。
I tried many approaches so far without success.
推荐答案
您的解决方案可能有效,但更好的方法是使用<一个href=\"https://msdn.microsoft.com/en-us/library/system.web.http.apicontroller.validate(v=vs.118).aspx\"相对=nofollow> ApiController.Validate 方法。
Your solution probably works, but a better way is using ApiController.Validate method.
public void MoviesController_Post_Without_Name()
{
// Arrange
var model = new MovieModel();
model.Name = "";
// Act
controller.Validate(model); //<---- use the built-in method
var result = controller.Post(model);
// Assert
Assert.IsInstanceOfType(result, typeof(InvalidModelStateResult));
Assert.AreEqual(6, controller.Get().Count());
}
这篇关于在Asp.Net MVC网页API ModelState.IsValid总是正确的测试控制器的时候,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!