Unit test controller model validation on AspNetCore

后端 未结 2 526
孤街浪徒
孤街浪徒 2021-01-01 23:07

In an ASPNET Core project I am trying to create some unit tests that would verify my data validation logic works fine.

My controller is very simple:

         


        
相关标签:
2条回答
  • 2021-01-01 23:34

    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

    0 讨论(0)
  • 2021-01-01 23:44

    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);
    
    0 讨论(0)
提交回复
热议问题