How do I unit test model validation in controllers decorated with [ApiController]?

我的未来我决定 提交于 2019-12-01 22:52:07

If you want to validate that the api's are returning a badrequest when the data annotations are broken then you need to do an api integration test. One nice option is to run the integration tests via an in-memory client using the TestServer

Here's an example:

//arrange
var b = new WebHostBuilder()
    .UseStartup<YourMainApplication.Startup>()
    .UseEnvironment("development");

var server = new TestServer(b) { BaseAddress = new Uri(url) };
var client = server.CreateClient();
var json = JsonConvert.SerializeObject(yourInvalidModel);
var content = new StringContent(json, Encoding.UTF8, "application/json");

//act
var result = await client.PostAsync("api/yourController", content);

//assert
Assert.AreEqual(400, (int)result.StatusCode);

If you only need to make sure that the annotations is proper setup you can manually trigger the validation via the TryValidateObject method

var obj = new YourClass();
var context = new ValidationContext(obj);
var results = new List<ValidationResult>();
var valid = Validator.TryValidateObject(obj, context, results, true);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!