Search code examples
c#.net-coreannotationsrequired

Required annotation on method parameters can be tested?


The [Required] annotation working fine while running, but can i test it with unit tests?

I tried debugging it, but seems the test is just jumping into, because of the direct call of the method.

Test:

var result = (StatusCodeResult)await this.Sut.Values(1, null);

result.StatusCode.Should().Be(HttpStatusCode.BadRequest);

Method:

public async Task<IActionResult> Values(int identifier, [Required] SomeType query)
{
    var readResult= await this.resultProvider.GetValues(identifier, query);
    if (readResult.Failed)
    {
        var error = new ErrorRepresentation(resultReadResult.Message);

        return this.StatusCode(error.StatusCode);
    }

    return this.Ok(readResult.Value);
}

I should get http response with 400 code, but i get 404 not found.


Solution

  • My guess is that it looks for an alternate method who have the second parameter on optional but doesn't find it, thus the 404.

    It's a routing issue, try to add a custom route for your test.