简体   繁体   中英

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

In our .Net Core 3.1 project we log using 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. I have a repository that uses both a DbContext and a Serilog logger.

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:

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

Serilog configuration:

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

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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