How to unit test with ILogger in ASP.NET Core

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

This is my controller:

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


        
14条回答
  •  不知归路
    2020-12-04 12:17

    Adding my 2 cents, This is a helper extension method typically put in a static helper class:

    static class MockHelper
    {
        public static ISetup> MockLog(this Mock> logger, LogLevel level)
        {
            return logger.Setup(x => x.Log(level, It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny>()));
        }
    
        private static Expression>> Verify(LogLevel level)
        {
            return x => x.Log(level, 0, It.IsAny(), It.IsAny(), It.IsAny>());
        }
    
        public static void Verify(this Mock> mock, LogLevel level, Times times)
        {
            mock.Verify(Verify(level), times);
        }
    }
    
    
    

    Then, you use it like this:

    //Arrange
    var logger = new Mock>();
    logger.MockLog(LogLevel.Warning)
    
    //Act
    
    //Assert
    logger.Verify(LogLevel.Warning, Times.Once());
    

    And of course you can easily extend it to mock any expectation (i.e. expection, message, etc …)

    提交回复
    热议问题