Unit test controller model validation on AspNetCore

假装没事ソ 提交于 2019-12-01 06:33:40

You should take a look at Integration Testing with ASP.NET Core (https://docs.microsoft.com/en-us/aspnet/core/testing/integration-testing), it is a very simple way to host your application in a test context and test your entire pipeline.
As explained in the documentation you could do something like this in your test method:

_server = new TestServer(new WebHostBuilder().UseStartup<Startup>());
_client = _server.CreateClient();
// Pass a not valid model 
var response = await _client.PostAsJsonAsync("Track", new DataItem());
Assert.IsFalse(response.IsSuccessStatusCode);

If you want to do a pure unit test you need to manually simulate the model state error because the model state validation is only triggered during runtime.

_myController.ModelState.AddModelError("yourItemFieldHere", "Your validation type here");

See https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/testing for more detail

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!