如何将 Serilog 添加到单元测试的服务集合中

How do I add Serilog to a service collection for my unit test

在我们的 .Net Core 3.1 项目中,我们使用 Serilog 进行日志记录

在测试的 set-up 中,我创建了一个 ServiceCollection,这样我就可以使用服务集合 \ - 提供程序更新我在测试中使用的 classes。 我有一个同时使用 DbContext 和 Serilog 记录器的存储库。

using Serilog;
using Microsoft.EntityFrameworkCore;

namespace MyApp.Persistency
{
    public class MyRepository : IMyRepository

{
    private readonly DataContext _dataContext;
    private readonly ILogger _logger;

    public OpvragenOnbekendeBurgerRegistratieRepository(DataContext dataContext, ILogger logger)
    {
        _dataContext = dataContext;
        _logger = logger;
    }
...
}

在我的测试中class:

    [TestInitialize]
    public void Initialize()
    {
         var diCollection =
         new ServiceCollection()
             .AddSingleton(new SqlConnectionOption(_connectionstring))
             .AddDbContext<DataContext>(
                options =>
                {
                   options.UseSqlServer(_connectionstring);
                }
              )
              ...               
              xxx Add some kind of Serilog registration xxx
              ...
              .AddTransient<IMyRepositoy,MyRepository>();
           _di = diCollection.BuildServiceProvider;
      }

    [TestMethod]
    public void MyRepositoryTest()
    {  
        // arrange
        var myRepository = _di.GetRequiredService<IMyRepository>();
        ...
    }

我看过无数不同的代码示例,但 none 似乎只适用于一个容器,而不是一个完整的 吹主机。一个什么都不记录的假人是可以接受的,但记录到测试控制台当然是史诗般的。

将 Serilog 添加到 ServiceCollection 实例:

new ServiceCollection()
    //...
    .AddLogging(builder => builder.AddSerilog(dispose: true))
    //...

Serilog 配置:

Log.Logger = new LoggerConfiguration()
    //...
    .CreateLogger();

Documentation