How do you mock ILogger LogInformation

前端 未结 5 1640
太阳男子
太阳男子 2020-12-10 12:59

I have a class that receives an ILogger and I want to mock the LogInformation calls but this is an extension method. How do I make the appropiate setup call for this?

5条回答
  •  执念已碎
    2020-12-10 13:19

    This is how I workaround for Moq (v4.10.1) framework.

    public static class TestHelper
    { 
    
        public static Mock> GetMockedLoggerWithAutoSetup()
        {
            var logger = new Mock>();
    
            logger.Setup(x => x.Log(
           It.IsAny(),
           It.IsAny(),
           It.IsAny(),
           It.IsAny(),
           It.IsAny>()));
    
            return logger;
        }
    
        public static void VerifyLogMessage(Mock> mockedLogger, LogLevel logLevel, Func predicate, Func times)
        {
            mockedLogger.Verify(x => x.Log(logLevel, 0, It.Is(p => predicate(p.ToString())), null, It.IsAny>()), times);
        }
    }
    
    
    

    --

    public class Dummy
    {
    
    }
    
    [Fact]
    public void Should_Mock_Logger()
    {
        var logger = TestHelper.GetMockedLoggerWithAutoSetup();
        logger.Object.LogInformation("test");
        TestHelper.VerifyLogMessage(logger, LogLevel.Information, msg => msg == "test", Times.Once);
    }
    

    --

    The thing is,

    If I had chosen any other than for logger.Setup(), it would fail on Verify step saying that 0 calls were made for x.Log and showing a call made to x.Log. So I setup my generic logger to mock Log(..) method instead.

    提交回复
    热议问题