繁体   English   中英

如何将日志从 TestServerFixture 重定向到 .net Core 中的 ITestOutputHelper?

[英]How to get redirect Log from TestServerFixture to ITestOutputHelper in .net Core?

我目前在 VSTS 的构建机器上测试失败,很难知道发生了什么。 我有很多由 API 生成的日志,它们可能非常有用。

我的目的是将我的 API 中生成的所有日志重定向到 OutputTestHelper。

使用 Xunit,我有一个 TestServerFixture:

 public class TestServerFixture : IDisposable
    {
        public TestServer Server { get; }
        public HttpClient Client { get; }
        public T GetService<T>() => (T)Server.Host.Services.GetService(typeof(T));

        public TestServerFixture()
        {
            var builder = new WebHostBuilder()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseEnvironment("Development")
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                          .AddEnvironmentVariables();
                })
                .UseStartup<TestStartup>()
                .ConfigureLogging((hostingContext, logging) =>
                {

                    logging.AddXunit(output); //How Can I get ITestOuputHelper?
                });

            Server = new TestServer(builder);
            Client = Server.CreateClient();
        }
        public void Dispose()
        {
            Server.Dispose();
            Client.Dispose();
        }
    }

读这个:

我有一个扩展,允许我将 Xunit ITestOutputHelper 添加到需要ITestOutputHelper作为参数的记录器( AddXunit() )。

问题是,我没有找到在 TestServerFixture 中获取它的方法。 我试过:

  • 也许在 TestServerFixture 的构造函数中有一些可用的注入可以实例 ITestOutputHelper ? public TestServerFixture(ITestOutputHelper output) => FAILED

  • 也许有一种方法可以从 IloggingBuilder.Services theITestOutputHelper(例如loggingBuilder.Services.Resolve<ITestOutputHelper>() )=> FAILED

  • 也许我可以从 TestStartup 的Configure方法中得到它(比如public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory, ITestOutputHelper output) )=> FAILED

您知道一种配置 TestServerFixture 以将所有日志重定向到 OutpuTestHelper 的方法吗?

如果你的 DI(包括ILoggerFactory )已经在你的装置上配置了一个记录器提供者实现,它写入 xUnit 输出,那么你应该能够从你的装置上的服务提供者请求ILogger<whatever> (使用GetService<T>您在那里向我们展示的方法)。

Microsoft 的记录器 DI 集成注册服务ILogger<>以提供来自 LoggerFactory 的记录器(为此您需要注册一个提供程序,这就是您在ConfigureLogging调用中使用AddXunit扩展所做的)

我终于找到了解决方案。 由于无法从 Injection 访问 ITestOutpuHelper,因此我没有其他方法可以为每个 Test 类创建一个新的 TestServerFixture。

我以前的东西:

public class Users_Tests
{
    [...]
    public Users_Tests(
        TestServerFixture server
        ITestOutputHelper output
    )
    {
        [...]
    }
}

我现在所拥有的:

public class Users_Tests
{
    [...]
    public Users_Tests(
        ITestOutputHelper output
    )
    {
        TestServerFixture = new TestServerFixture(output);    
        [...]
    }
}

所以我的 TestServiceFixture 现在是:

public class TestServerFixture : IDisposable
{
    public TestServer Server { get; }
    public HttpClient Client { get; }
    public T GetService<T>() => (T)Server.Host.Services.GetService(typeof(T));

    public TestServerFixture(ITestOutputHelper output)
    {
        var builder = new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseEnvironment("Development")
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                      .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                      .AddEnvironmentVariables();
            })
            .UseStartup<TestStartup>()
            .ConfigureLogging((hostingContext, logging) =>
            {
                logging.AddXunit(output);
            });

        Server = new TestServer(builder);
        Client = Server.CreateClient();
    }
    public void Dispose()
    {
        Server.Dispose();
        Client.Dispose();
    }
}

所以现在所有日志都被重定向到输出,这帮助我了解错误来自哪里!

如果您没有通过ITestOutputHelper获取日志的严格要求,您可以尝试使用 xUnit 中的IMessageSink抽象,在 TestFixtures 中进行日志记录。

public class SutTests : IClassFixture<TestServerFixture>
{
    private readonly ITestOutputHelper _output; // for logging inside test classes
    private readonly TestServerFixture  _fixture;

    public SutTests(TestServerFixture fixture, ITestOutputHelper output) {
        _fixture = fixture
        _output = output;
    }
    ...
}

public class TestServerFixture : IAsyncLifetime
{
    private readonly IMessageSink _sink; // for logging inside TestFixtures
    public TestServerFixture(IMessageSink sink) {
        _sink = sink;
        _sink.OnMessage(new DiagnosticMessage("Test Server Fixture Created."));
    }

    public async Task InitializeAsync() {
        // initialize stuffs..
        _sink.OnMessage(new DiagnosticMessage("Fixture initialized."));
    }
    ...
}

注意事项

  • 您需要在 Xunit 配置文件中 启用诊断消息
  • 您需要 XUnit 2.4.1或更高版本。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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