Aspnetcore: Better Error Message in ControllerBase.ValidationProblem

Created on 18 Oct 2019  路  4Comments  路  Source: dotnet/aspnetcore

Describe the bug

During Unit Tests, I was getting a NullReferenceExeption in ControllerBase.ValidationProblem. Difficult to narrow down the problem.

To Reproduce

Steps to reproduce the behavior:

  1. 3.0.0
  2. Create a controller unit test of an action that calls ValidationResult.
var c  = new MyController();
c.MyAction(); // Should call return new ValidationResult;
  1. NullReferenceException was due to ProblemDetailsFactory being null, as ProblemDetailsFactory => HttpContext?.RequestServices?.GetRequiredService<ProblemDetailsFactory>() silently returns null.

Expected behavior

Error message should be actual problem. NullReferenceException is not clear. Perhaps check for null when returning ProblemDetailsFactory property.

Additional context

Add any other context about the problem here.
Include the output of dotnet --info

Done area-mvc help wanted task

Most helpful comment

Hi, i'm issuing the exact same issue only on unit test. On my controller code I'm doing something like this :

public IActionResult Foo([FromBody] Command request)
    {
        ModelState.AddModelError<Command>(a => a.Bar, "Invalid.");
        return ValidationProblem();
    }

On normal execution it works but on unit test I got NullReferenceException.

If I replace ValidationProblem() by BadRequest(ModelState), it works both in unit test and on normal execution. But the response with BadRequest doesn't have all the property of RFC 7807.

How do you handle this error on unit test on your side ?

Thanks in advance

All 4 comments

Thanks for the issue report @bradlis7. We'd be happy to accept a PR to improve the error message here if you'd like to send one.

Hi, i'm issuing the exact same issue only on unit test. On my controller code I'm doing something like this :

public IActionResult Foo([FromBody] Command request)
    {
        ModelState.AddModelError<Command>(a => a.Bar, "Invalid.");
        return ValidationProblem();
    }

On normal execution it works but on unit test I got NullReferenceException.

If I replace ValidationProblem() by BadRequest(ModelState), it works both in unit test and on normal execution. But the response with BadRequest doesn't have all the property of RFC 7807.

How do you handle this error on unit test on your side ?

Thanks in advance

Hello I am facing the exact same issue as Nagarian, we want to use the RFC Response but our unittests Fail because of that Problem.

Thank you

Was this page helpful?
0 / 5 - 0 ratings