[英]TryValidateModel in asp.net core throws Null Reference Exception while performing unit test
[英]ASP.NET Core unit test throws Null Exception when testing controller problem response
我正在为我的项目创建基本的单元测试。 出于某种原因,在测试我收到ControllerBase.Problem(String, String, Nullable<Int32>, String, String)
响应时,我不断收到 NullReferenceException。 我确信问题是与 controller 没有实际运行的差异,因为它在 controller 运行时表现得非常好。
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);
}
测试:
[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);
}
结果:
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
正如 Aluan Haddad 在评论中所指出的,那个Problem()
调用ProblemDetailsFactory
来创建由服务管理器提供的ProblemDetails
对象。 服务管理器仅在应用程序运行时工作:https://github.com/dotnet/aspnetcore/blob/master/src/Mvc/Mvc.Core/src/ControllerBase.cs#L194
可以设置ControllerBase.ProblemDetailsFactory
变量,因此我创建了一个模拟ProblemDetailsFactory
实例并将控制器工厂设置为我的模拟实例。 这似乎使它起作用。
嘲笑:
public class MockProblemDetailsFactory : ProblemDetailsFactory
{
public MockProblemDetailsFactory()
{
}
public override ProblemDetails CreateProblemDetails(HttpContext httpContext,
int? statusCode = default, string title = default,
string type = default, string detail = default, string instance = default)
{
return new ProblemDetails() {
Detail = detail,
Instance = instance,
Status = statusCode,
Title = title,
Type = type,
};
}
public override ValidationProblemDetails CreateValidationProblemDetails(HttpContext httpContext,
ModelStateDictionary modelStateDictionary, int? statusCode = default,
string title = default, string type = default, string detail = default,
string instance = default)
{
return new ValidationProblemDetails(new Dictionary<string, string[]>()) {
Detail = detail,
Instance = instance,
Status = statusCode,
Title = title,
Type = type,
};
}
}
我在这个单元测试的设置中添加了这一行,它解决了这个问题。
_patientController.ProblemDetailsFactory = new MockProblemDetailsFactory();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.