如何在装饰有[ApiController]的控制器中进行单元测试模型验证? [英] How do I unit test model validation in controllers decorated with [ApiController]?

查看:154
本文介绍了如何在装饰有[ApiController]的控制器中进行单元测试模型验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此答案中指出的Asp.Net Core 2.1 ApiController不会在单元测试下自动验证模型,即自动的ModelState验证ASP.NET Core 2.1的ApiControllerAttribute仅在运行时实际请求操作时起作用,而不是通过在单元测试中使用无效参数来调用该操作.

As pointed out in this anwer to Asp.Net Core 2.1 ApiController does not automatically validate model under unit test, the automatic ModelState validation that ASP.NET Core 2.1's ApiControllerAttribute gives us only works when actualyy requestion the action at runtime, not by calling it with an invalid parameter in a unit test.

但是,我仍然想在提供不正确的模型时测试我的操作是否实际上返回BadRequestResult.有什么办法吗?我知道我仍然可以手动检查ModelState.IsValid是否为false,然后自己返回BadRequest(),但是这种方法无法实现自动验证的目的.

However, I still want to test if my action actually returns a BadRequestResult when supplying an incorrect model. Is there any way of doing this? I get that I can still manually check if ModelState.IsValid is false, and returning BadRequest() myself, but that kind of defeats the point of the automatic validation.

我还是坚持手动检查ModelState.IsValid,还是有一种方法可以在单元测试中使用新的ApiControllerAttribute模型验证?

Am I stuck manually checking ModelState.IsValid after all, or is there a way to make use of the new ApiControllerAttribute model validation in a unit test?

推荐答案

如果要验证在数据注释中断时api是否正在返回badrequest,则需要进行api集成测试. 一个不错的选择是使用 TestServer通过内存中的客户端运行集成测试.

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

这是一个例子:

//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);

这篇关于如何在装饰有[ApiController]的控制器中进行单元测试模型验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆