简体   繁体   English

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

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

In our .Net Core 3.1 project we log using Serilog在我们的 .Net Core 3.1 项目中,我们使用 Serilog 进行日志记录

In the set-up of my test I create a ServiceCollection so I can new up my classes I use in the tests using a service collection \\ - provider.在我的测试设置中,我创建了一个 ServiceCollection,这样我就可以使用服务集合 \\ - 提供者来更新我在测试中使用的类。 I have a repository that uses both a DbContext and a Serilog logger.我有一个同时使用 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;
    }
...
}

In my test 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>();
        ...
    }

I have seen a zillion different code samples, but none seem to work only a container, instead of a full blown host.我见过无数不同的代码示例,但似乎没有一个只能在容器中工作,而不是在完整的主机上工作。 A dummy that logs nothing would be acceptable, but logging to the testconsole would of course be epic.一个不记录任何内容的虚拟人是可以接受的,但登录到测试控制台当然是史诗般的。

Add Serilog to a ServiceCollection instance:将 Serilog 添加到ServiceCollection实例:

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

Serilog configuration:串口配置:

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

Documentation文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM