abpframework / abpframework/abp

Logger dependency injection in xUnit test project.

Open
#12,092 3 comments 1 reaction 1 assignee View on GitHub

@maliming is already working on this.

Since Mar 27, 2022.

Dominant language
C#
Stars
14.4k
Forks
3.7k
Avg merge
15h 32m
Merged PRs (30d)
106

Description

relate #3012

I want to make all loggers in my project works with xUnit.

That means I need to register Serilog to the ServiceCollection.

But there is a trouble about class AbpIntegratedTest. It will call the all initialization methods from constructor. And ServiceProvider will be built from constructor too.

As a well-known, the derived class constructor will be executed after the base constructor. And the ITestOutputHelper instance must be get from constructor.

That cause I can't get the ITestOutputHelper instance when I configure the services.

So, I want to make a pull request to integrate logging with test project:

  1. Add a constructor AbpIntegratedTest(ITestOutputHelper testOutputHelper). The parameterless constructor will be kept and forward to the new constructor. It means the parameter is optional. You can ignore the parameter if you don't care logging.
  2. Add an empty virtual method void ConfigureLogging(LoggingBuilder builder) to class AbpIntegratedTest. It will be called from the constructor after AfterAddApplication.
  3. Also add the constructors to template class MyProjectNameTestBase. And add a default implementation of ConfigureLogging, it need to import a dependency Serilog.Sinks.XUnit.:
public MyProjectNameTestBase() {}

public MyProjectNameTestBase(ITestOutputHelper testOutputHelper) : base(testOutputHelper) {}

protected override void ConfigureLogging(ILoggingBuilder builder)
{
    if (TestOutputHelper == null) return; // The TestOutputHelper is a get-only property in AbpIntegratedTest.

    Log.Logger = new LoggerConfiguration()
#if DEBUG
        .MinimumLevel.Debug()
#else
        .MinimumLevel.Information()
#endif
        .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
        .Enrich.FromLogContext()
        .WriteTo.TestOutput(TestOutputHelper)
        .CreateLogger();

    builder.AddSerilog();
}

Then we can use all logging features in my tests, that only need to pass the ITestOutputHelper to the base class. And it won't break any exists codes.

What do you think about this?

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.