How do you mock ILogger LogInformation

前端 未结 5 1647
太阳男子
太阳男子 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:36

    ILogger is normally used thru extension methods, LogWarning, LogError, etc.

    In my case I was interested in the LogWarning method which after looking at the code calls the Log method from ILogger. In order to mock it with Moq, this is what I ended up doing:

     var list = new List();
                var logger = new Mock();
                logger
                    .Setup(l => l.Log(LogLevel.Warning, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()))
                    .Callback(
                    delegate (LogLevel logLevel, EventId eventId, FormattedLogValues state, Exception exception, Func formatter)
                    {
                        list.Add(state.ToString());
                    });
    

提交回复
热议问题