How to unit test with ILogger in ASP.NET Core

后端 未结 14 1254
南旧
南旧 2020-12-04 11:47

This is my controller:

public class BlogController : Controller
{
    private IDAO _blogDAO;
    private readonly ILogger _         


        
14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-04 12:10

    Merely creating a dummy ILogger is not very valuable for unit testing. You should also verify that the logging calls were made. You can inject a mock ILogger with Moq but verifying the call can be a little tricky. This article goes into depth about verifying with Moq.

    Here is a very simple example from the article:

    _loggerMock.Verify(l => l.Log(
    LogLevel.Information,
    It.IsAny(),
    It.IsAny(),
    It.IsAny(),
    (Func)It.IsAny()), Times.Exactly(1));
    
    

    It verifies that an information message was logged. But, if we want to verify more complex information about the message like the message template and the named properties, it gets more tricky:

    _loggerMock.Verify
    (
        l => l.Log
        (
            //Check the severity level
            LogLevel.Error,
            //This may or may not be relevant to your scenario
            It.IsAny(),
            //This is the magical Moq code that exposes internal log processing from the extension methods
            It.Is((state, t) =>
                //This confirms that the correct log message was sent to the logger. {OriginalFormat} should match the value passed to the logger
                //Note: messages should be retrieved from a service that will probably store the strings in a resource file
                CheckValue(state, LogTest.ErrorMessage, "{OriginalFormat}") &&
                //This confirms that an argument with a key of "recordId" was sent with the correct value
                //In Application Insights, this will turn up in Custom Dimensions
                CheckValue(state, recordId, nameof(recordId))
        ),
        //Confirm the exception type
        It.IsAny(),
        //Accept any valid Func here. The Func is specified by the extension methods
        (Func)It.IsAny()),
        //Make sure the message was logged the correct number of times
        Times.Exactly(1)
    );
    
    

    I'm sure that you could do the same with other mocking frameworks, but the ILogger interface ensures that it's difficult.

    提交回复
    热议问题