单元测试自定义 MessageHandler

Unit testing Custom MessageHandler

我有一个自定义处理程序如下:

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;
     }
}

我熟悉最小起订量,我能够最小起订量请求和响应消息并成功断言。

然而,如您所见,我在 SendAsync 方法中完成了记录器初始化,并记录了有关请求、响应和错误的信息。

如何在此工作流程中测试记录器?

问题在于,由于记录器是手动初始化的,因此很难对其进行模拟。

记录器应该是注入的依赖项。

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;
    }

    //...