I'm creating basic unit tests for my project. For some reason, I keep getting a NullReferenceException when testing that I get a ControllerBase.Problem(String, String, Nullable<Int32>, String, String) response. I'm sure the problem is a discrepancy from the controller not actually running, as it seems to behave perfectly fine when the controller is running.
Controller:
[HttpGet("{id}")]
[Produces("application/json")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetPatient([GuidNotEmpty] Guid id)
{
Patient patient = null;
patient = _patientDbService.FindPatient(id);
if (patient == null) {
return Problem("Patient not found.", string.Empty, StatusCodes.Status404NotFound,
"An error occurred.", "https://tools.ietf.org/html/rfc7231#section-6.5.1");
}
return Ok(patient);
}
Test:
[Fact]
public void TestGetPatientFromIdPatientNotFound()
{
// Act
IActionResult result = _patientController.GetPatient(Guid.NewGuid());
// Assert
Assert.IsType<ObjectResult>(result);
Assert.NotNull(((ObjectResult)result).Value);
Assert.IsType<ProblemDetails>(((ObjectResult)result).Value);
Assert.Equal(((ObjectResult)result).StatusCode, StatusCodes.Status404NotFound);
}
Result:
X PatientServiceTest.PatientServiceUnitTest.TestGetPatientFromIdPatientNotFound [1ms]
Error Message:
System.NullReferenceException : Object reference not set to an instance of an object.
Stack Trace:
at Microsoft.AspNetCore.Mvc.ControllerBase.Problem(String detail, String instance, Nullable`1 statusCode, String title, String type)
at PatientService.Controllers.PatientController.GetPatient(Guid id) in /home/surafel/coding/microservices-dev/c#/PatientService/Controllers/PatientController.cs:line 43
at PatientServiceTest.PatientServiceUnitTest.TestGetPatientFromIdPatientNotFound() in /home/surafel/coding/microservices-dev/c#/PatientServiceTest/PatientServiceUnitTest.cs:line 69
_patientController? How are you specifying its dependencies?ControllerBaserelies on various framework level services.BadRequestObjectResultinstead of justObjectResult.Problemcall in a try-catch loop, and create my ownProblemDetailsbe a proper solution?