安装 nuget 包 Serilog.Sinks.XUnit
dotnet add package Serilog.Sinks.XUnit
在 CustomWebApplicationFactory 类中实现 ConfigureLogging() 方法
public class CustomWebApplicationFactory<TStartup> :
WebApplicationFactory<TStartup> where TStartup : class
{
public void ConfigureLogging(ITestOutputHelper outputHelper)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.TestOutput(outputHelper, LogEventLevel.Information)
.CreateLogger();
}
}
在测试类的构造函数中通过依赖注入获取 ITestOutputHelper ,然后调用上面的 ConfigureLogging() 方法配置 Serilog 将日志输出到 ITestOutputHelper
public class WebApiTest : IClassFixture<CustomWebApplicationFactory<Startup>>
{
private readonly HttpClient _httpClient;
public WebApiTest(CustomWebApplicationFactory<Startup> factory, ITestOutputHelper testOutput)
{
factory.ConfigureLogging(testOutput);
_httpClient = factory.CreateClient();
}
//...
}