Skip to content

Testing DelegatingHandlers

Diego Faria edited this page Dec 1, 2023 · 2 revisions

Here is an example to test Delegating Handlers. Here is an example delegating handler

    public class HandlerToTest: DelegatingHandler
    {
        ILogger<HandlerToTest> _logger;
        public HandlerToTest(ILogger<HandlerToTest> logger)
        {
            _logger = logger;
        }
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
             _logger.LogInformation($"Test Me out {response.StatusCode}");
            return response;
        }
    }

To set up your test you will need to do the following

    public class HandlerToTestSpecs
    {
        protected readonly MockHttpMessageHandler httpMock = new MockHttpMessageHandler();
        protected readonly Mock<ILogger<HandlerToTest>> _logger = new Mock<ILogger<HandlerToTest>>();

        protected HttpMessageInvoker MakeSut()
        {
            var subject = new HandlerToTest(_logger.Object);
            subject.InnerHandler = httpMock;
            return new HttpMessageInvoker(subject);
        }
    }

Here is an example test

     public class SendAsyncTests : HandlerToTestSpecs
     {
        [Fact]
        public async Task Should_log()
        {

            var uri = new Uri("http://localhost/test");
            httpMock.Expect(uri.ToString()).Respond("application/json", "{}");

            var invoker = MakeSut();
            HttpRequestMessage message = new HttpRequestMessage();
            message.Method =  HttpMethod.Post;
            message.RequestUri = uri;

            

            await invoker.SendAsync(message,
                new System.Threading.CancellationToken());


            _logger.VerifyMessage(
           LogLevel.Information,
           $"Test Me out {HttpStatusCode.OK}");

        
            httpMock.VerifyNoOutstandingRequest();


        }
    }

Where the extension method for the ILogger is

    public static class MockLoggerExtensions
    {
        public static Mock<ILogger<T>> VerifyMessage<T>(this Mock<ILogger<T>> logger, LogLevel level, string expectedMessage)
        {
            Func<object, Type, bool> state = (v, t) => v.ToString().CompareTo(expectedMessage) == 0;

            logger.Verify(
                x => x.Log(
                    It.Is<LogLevel>(l => l == level),
                    It.IsAny<EventId>(),
                    It.Is<It.IsAnyType>((v, t) => state(v, t)),
                    It.IsAny<Exception>(),
                    It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)));

            return logger;
        }
    }
Clone this wiki locally