abpframework / abpframework/abp
Logger dependency injection in xUnit test project.
@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:
- 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. - Add an empty virtual method
void ConfigureLogging(LoggingBuilder builder)to classAbpIntegratedTest. It will be called from the constructor afterAfterAddApplication. - Also add the constructors to template class
MyProjectNameTestBase. And add a default implementation ofConfigureLogging, it need to import a dependencySerilog.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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Assessment
This issue has not been assessed yet.