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

后端 未结 1 956
南旧
南旧 2021-01-21 13:51

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\'

相关标签:
1条回答
  • 2021-01-21 14:39

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