1

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?.

Nkosi
  • 235,767
  • 35
  • 427
  • 472
kauschan
  • 446
  • 2
  • 8
  • 21
  • 1
    problem will be that because of the manual initialization of the logger it is difficult to mock it. The logger should have been an injected dependency. If injection is not an option then have a virtual factory method that can be overridden when testing. – Nkosi Jun 13 '18 at 01:51
  • the problem with that is my logger takes in the correlationId got from the HttpContext. The handler is added as a messageHandler to the webApi config . I would not be able to initialize the logger there as context would be null until I get the first request. – kauschan Jun 13 '18 at 02:04

1 Answers1

1

Problem will be that because of the manual initialization of the logger it is difficult to mock it.

The logger should have been an injected dependency.

public class LoggingHandler : DelegatingHandler {
    private readonly ILogger logger;

    public LoggingHandler(ILogger logger) {
        this.logger = logger;
    }

    //...

If injection is not an option then have a virtual factory method that can be overridden when testing.

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

    //...
Nkosi
  • 235,767
  • 35
  • 427
  • 472
  • Thanks I was afraid I would need to be create a factory method . Just thought to check if there's any other way . Thank you for the response – kauschan Jun 13 '18 at 02:14