首页 > 解决方案 > 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?.

标签: c#unit-testingasp.net-web-apimoqmessage-handlers

解决方案


问题是由于记录器的手动初始化,很难模拟它。

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

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

    //...

推荐阅读