How to unit test with ILogger in ASP.NET Core

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

This is my controller:

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


        
14条回答
  •  我在风中等你
    2020-12-04 12:23

    I've tried to mock that Logger interface using NSubstitute (and failed because Arg.Any() requeres a type parameter, which I can't provide), but ended up creating a test logger (similarly to @jehof's answer) in the following way:

        internal sealed class TestLogger : ILogger, IDisposable
        {
            private readonly List _messages = new List();
    
            public IReadOnlyList Messages => _messages;
    
            public void Dispose()
            {
            }
    
            public IDisposable BeginScope(TState state)
            {
                return this;
            }
    
            public bool IsEnabled(LogLevel logLevel)
            {
                return true;
            }
    
            public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func formatter)
            {
                var message = formatter(state, exception);
                _messages.Add(new LoggedMessage(logLevel, eventId, exception, message));
            }
    
            public sealed class LoggedMessage
            {
                public LogLevel LogLevel { get; }
                public EventId EventId { get; }
                public Exception Exception { get; }
                public string Message { get; }
    
                public LoggedMessage(LogLevel logLevel, EventId eventId, Exception exception, string message)
                {
                    LogLevel = logLevel;
                    EventId = eventId;
                    Exception = exception;
                    Message = message;
                }
            }
        }
    

    You can easily access all logged messages and assert all meaningful parameters provided with it.

提交回复
热议问题