Model state validation in unit tests

后端 未结 4 671
予麋鹿
予麋鹿 2020-12-08 14:44

I am writing a unit test for a controller like this:

public HttpResponseMessage PostLogin(LoginModel model)
{
    if (!ModelState.IsValid)
        return new         


        
4条回答
  •  忘掉有多难
    2020-12-08 14:54

    As mentioned before, you need integration tests to validate the ModelState. So, with Asp.Net Core, I'm digging this question to add a simple solution for integrating tests with Asp.Net Core and validation of ModelState

    Add the package Microsoft.AspNetCore.TestHost and you can submit requests this simple:

    var server = new TestServer(new WebHostBuilder().UseStartup());
    var client = server.CreateClient();
    var model = new { Name = String.Empty };
    var content = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
    var result = await client.PostAsync("/api/yourApiEndpoint", content);
    result.StatusCode.Should().Be(HttpStatusCode.BadRequest);
    

    You can find more about it here: http://asp.net-hacker.rocks/2017/09/27/testing-aspnetcore.html

    Hope it helps.

提交回复
热议问题