How to unit test with ILogger in ASP.NET Core

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

This is my controller:

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


        
14条回答
  •  悲哀的现实
    2020-12-04 12:13

    Actually, I've found Microsoft.Extensions.Logging.Abstractions.NullLogger<> which looks like a perfect solution. Install the package Microsoft.Extensions.Logging.Abstractions, then follow the example to configure and use it:

    using Microsoft.Extensions.Logging;
    
    public void ConfigureServices(IServiceCollection services)
    {
        ...
    
        services.AddSingleton();
    
        ...
    }
    
    using Microsoft.Extensions.Logging;
    
    public class MyClass : IMyClass
    {
        public const string ErrorMessageILoggerFactoryIsNull = "ILoggerFactory is null";
    
        private readonly ILogger logger;
    
        public MyClass(ILoggerFactory loggerFactory)
        {
            if (null == loggerFactory)
            {
                throw new ArgumentNullException(ErrorMessageILoggerFactoryIsNull, (Exception)null);
            }
    
            this.logger = loggerFactory.CreateLogger();
        }
    }
    

    and unit test

    //using Microsoft.VisualStudio.TestTools.UnitTesting;
    //using Microsoft.Extensions.Logging;
    
    [TestMethod]
    public void SampleTest()
    {
        ILoggerFactory doesntDoMuch = new Microsoft.Extensions.Logging.Abstractions.NullLoggerFactory();
        IMyClass testItem = new MyClass(doesntDoMuch);
        Assert.IsNotNull(testItem);
    }   
    

提交回复
热议问题