【问题标题】:How to get redirect Log from TestServerFixture to ITestOutputHelper in .net Core?如何在 .net Core 中将日志从 TestServerFixture 重定向到 ITestOutputHelper?
【发布时间】:2019-08-30 20:24:28
【问题描述】:

我目前在 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 的构造函数中有一些可用的 Injection 可以实例化 ITestOutputHelper ? public TestServerFixture(ITestOutputHelper output) => 失败

  • 也许有办法从 IloggingBuilder.Services 中解决 ITestOutputHelper(如 loggingBuilder.Services.Resolve&lt;ITestOutputHelper&gt;())=> FAILED

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

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

【问题讨论】:

    标签: c# .net-core xunit.net


    【解决方案1】:

    如果您的 DI(包括 ILoggerFactory)已经在您的夹具上配置了一个写入 xUnit 输出的记录器提供程序实现,那么您应该能够从夹具上的服务提供商请求 ILogger&lt;whatever&gt;(使用您在其中向我们展示的GetService&lt;T&gt; 方法)。

    Microsoft 的记录器 DI 集成注册服务 ILogger&lt;&gt; 以提供来自 LoggerFactory 的记录器(您需要为此注册提供程序,这就是您在 AddXunit 调用上使用 AddXunit 扩展所做的事情)

    【讨论】:

    • 感谢您的帮助。据我了解,解决服务的唯一方法是构建您的 webhostbuilder,在 ConfigureLogging 中未构建 hostingContext,因此您无法解析服务,因此我不得不思考并找到解决方案的新方法: )
    【解决方案2】:

    我终于找到了解决办法。由于无法从 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();
        }
    }
    

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

    【讨论】:

    • 是的,这就行了。只需将 IHttpClientFactory 添加到 XUnit 测试的构造函数中,它就会被注入。
    【解决方案3】:

    如果您没有通过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."));
        }
        ...
    }
    

    注意事项:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-01
      • 2017-03-26
      • 1970-01-01
      • 2021-05-11
      • 2015-03-16
      • 1970-01-01
      • 2020-04-23
      相关资源
      最近更新 更多