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();