Search code examples
asp.net-corexunit.net.net-8.0

How to unit test .net automatic validation?


Ho Ho Community!

Curiosity, we start to migrate to .net 8.0 and discovered that .net is automatically validate missing parameters.

Here an example of a response from POST https://localhost/devices/activate

{
    "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "errors": {
        "deviceKey": [
            "The deviceKey field is required."
        ]
    },
    "traceId": "00-1d79adff75ce5947168a526dac7bdb70-4b612cd077628f9e-00"
}
  1. When this validation occur?

  2. I am surprised, usually, we were doing an unit test to validate that behavior and now it seems we need an integration test to trigger this response by calling the end-point? Is there any other way to get that response in the scope of an unit test, without running the application?

Thank you!


Solution

  • The [ApiController] attribute makes model validation errors automatically trigger an HTTP 400 response,you could check the document related

    If you debug with an invalid model,you would get the automatic response without getting into the controller at all, and when unit testing controller logic, only the contents of a single action are tested, not the behavior of its dependencies or of the framework itself.

    If you want to ensure app's components function correctly at a level that includes the app's supporting infrastructure,you should try with integration test