dotnet / aspnetcore

ASP.NET Core is a cross-platform .NET framework for building modern cloud-based web applications on Windows, Mac, or Linux.
https://asp.net
MIT License
35.23k stars 9.95k forks source link

Better Error Message in ControllerBase.ValidationProblem #15166

Closed bradlis7 closed 4 years ago

bradlis7 commented 4 years ago

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

pranavkm commented 4 years ago

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.

Nagarian commented 4 years ago

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

andrejreimer commented 4 years ago

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

Powerz commented 4 years ago

There is an awkward way to test ValidationProblem: https://stackoverflow.com/questions/60740134/how-to-unit-test-whether-a-core-mvc-controller-action-calls-controllerbase-probl