我创建了一个自定义的。net healthcheck
public static class HealthCheckHighMark
{
public static IEndpointConventionBuilder MapHighMarkChecks(
this IEndpointRouteBuilder endpoints)
{
return endpoints.MapHealthChecks("/api/health/highmark", new HealthCheckOptions
{
ResponseWriter = async (context, report) =>
{
var result = JsonConvert.SerializeObject(
new HighMarkResult
{
HighMark = HealthHandler.GetHighMark().High.ToString(),
}, Formatting.None,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
});
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(result);
},
Predicate = (check) => check.Tags.Contains("highmark")
});
}
}
我正试图写一个测试,以确保响应格式正确。它现在看起来像这样:
readonly Mock<IEndpointRouteBuilder> _mockIEndpointRouteBuilder = new Mock<IEndpointRouteBuilder>();
[Fact]
public async Task TestHighMarkResponse()
{
var _mockIHighMarkResult = Mock.Of<HighMarkResult>(m =>
m.HighMark == "100");
var response = HealthCheckHighMark.MapHighMarkChecks(_mockIEndpointRouteBuilder.Object);
}
我的问题是,当我运行测试时,我得到这个错误:
信息:系统。NullReferenceException:对象引用没有设置为对象的实例。堆栈跟踪:HealthCheckEndpointRouteBuilderExtensions。MapHealthChecksCore(IEndpointRouteBuilder端点,字符串模式,HealthCheckOptions选项)HealthCheckEndpointRouteBuilderExtensions。MapHealthChecks(IEndpointRouteBuilder端点,字符串模式,HealthCheckOptions选项)HealthCheckHighMark。MapHighMarkChecks(IEndpointRouteBuilder端点)第26行HealthCheckTests.TestHighMarkResponse()第108行——从抛出异常的前一个位置开始的堆栈跟踪结束——
问题似乎是MapHigharkChecks
返回null
。我怎样才能解决这个问题,使它返回HighMarkResult
?
这似乎是一个XY问题。
我正试图写一个测试,以确保响应格式正确
但是测试正在尝试调用健康检查配置/设置
将ResponseWriter
委托移动到自己的字段
public static class HealthCheckHighMark {
public static IEndpointConventionBuilder MapHighMarkChecks(
this IEndpointRouteBuilder endpoints) {
return endpoints.MapHealthChecks("/api/health/highmark", new HealthCheckOptions {
ResponseWriter = ResponseWriter, //<---
Predicate = (check) => check.Tags.Contains("highmark")
});
}
public static Func<HttpContext, HealthReport, Task> ResponseWriter =
async (context, report) => {
var result = new HighMarkResult {
HighMark = HealthHandler.GetHighark().High.ToString(),
};
var settings = new JsonSerializerSettings {
NullValueHandling = NullValueHandling.Ignore
};
string json = JsonConvert.SerializeObject(result, Formatting.None,settings);
context.Response.ContentType = MediaTypeNames.Application.Json;
await context.Response.WriteAsync(json);
};
}
这样就可以单独测试了。
[Fact]
public async Task TestHighMarkResponse() {
// Arrange
HttpContext context = new DefaultHttpContext();
var report = Mock.Of<HealthReport>();
Stream body = new MemoryStream();
context.Response.Body = body;
// Act - testing the code that actually does the work
await HealthCheckHighMark.ResponseWriter(context, report);
//Assert
//... read JSON from stream
body.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(body);
string json = reader.ReadToEnd();
//... and assert desired behavior
}