How to unit test with ILogger in ASP.NET Core

后端 未结 14 1225
南旧
南旧 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

    For .net core 3 answers that are using Moq

    • https://stackoverflow.com/a/54646657/2164198
    • https://stackoverflow.com/a/54809607/2164198
    • https://stackoverflow.com/a/56728528/2164198

      are no longer working due to a change described in the issue TState in ILogger.Log used to be object, now FormattedLogValues

    Luckily stakx provided a nice workaround. So I'm posting it in hope it can save time for others (it took a while to figure the things out):

     loggerMock.Verify(
                    x => x.Log(
                        LogLevel.Information,
                        It.IsAny(),
                        It.Is((o, t) => string.Equals("Index page say hello", o.ToString(), StringComparison.InvariantCultureIgnoreCase)),
                        It.IsAny(),
                        (Func) It.IsAny()),
                    Times.Once);
    
        

    提交回复
    热议问题