c# - Unit testing Custom MessageHandler
问题描述
I have a custom handler as below:
public class LoggingHandler : DelegatingHandler
{
public LoggingHandler()
{
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken)
{
var logger = new Logger(new something1(), param2, param3);
logger.LogInformation(
$"Incoming request: {request.Method} {request.RequestUri} );
.
.
.
.
return httpResponse;
}
}
I am familiar with Moq and I am able to moq the request and response message and assert successfully on that.
However as you can see I have a logger initialization done in the SendAsync
method and log information regarding request, response and errors.
How can I test the logger in this workflow?.
解决方案
问题是由于记录器的手动初始化,很难模拟它。
记录器应该是一个注入的依赖项。
public class LoggingHandler : DelegatingHandler {
private readonly ILogger logger;
public LoggingHandler(ILogger logger) {
this.logger = logger;
}
//...
如果注入不是一个选项,那么有一个虚拟工厂方法可以在测试时被覆盖。
public class LoggingHandler : DelegatingHandler {
public LoggingHandler() {
}
protected virtual ILogger CreateLogger() {
//...
}
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request,
CancellationToken cancellationToken) {
var logger = CreateLogger();
logger.LogInformation(
$"Incoming request: {request.Method} {request.RequestUri} );
//....
return httpResponse;
}
//...
推荐阅读
- javascript - 尝试访问表单处理程序中的状态会在本机反应中给出默认状态而不是更新状态
- java - 创建 okhttp3 请求正文以在 google drive 中创建文件夹
- excel - 具有多个条件的 Excel 求和公式
- javascript - 有什么方法可以简化这个 JavaScript 函数吗?
- html - Django 自定义 404 页面未按预期工作
- angular - 从应用程序组件到路由的 Angular 通信
- javascript - 使用 DocumentClient 存储时出现在 JSON 中的 DynamoDB WrapperName
- excel - 如何在 Excel 中点击超链接并关闭原始文件?
- ios - 匿名函数的 Swift 队列
- sql - SQL如何在已经使用max时获取最大日期