首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用TestServer进行集成测试时在中获取控制台日志记录

使用TestServer进行集成测试时在中获取控制台日志记录
EN

Stack Overflow用户
提问于 2021-10-28 20:00:27
回答 1查看 210关注 0票数 1

当直接使用我的模块执行集成测试(跳过API)时,我可以在Visual测试运行程序中获得控制台输出。

当我尝试使用TestServer执行集成测试(包括我的API )时,如果我在调试中运行,我会将所有的日志发送到debug窗口,但是在正常运行时,我不会在Visual测试运行程序中获得任何输出。

我正在使用NUnit。

集成测试设置(跳过API)

代码语言:javascript
复制
public class Tests
{
    private ILogger _loggerForModule;

    [SetUp]
    public void InitializeModule()
    {
        // Create the logger
        using (ILoggerFactory loggerFactory = LoggerFactory.Create(b =>
        {
            b.AddConsole();
            b.AddDebug();
        }))
        {
            _loggerForModule = loggerFactory.CreateLogger("Module.Logging");
        }

        // Initialize the module with the logger created for it.
        ModuleInitializer.Initialize(_loggerForModule);
    }

    [Test]
    public async Task TestMyMethod()
    {
        ModuleCommands.ExecuteCommand(new DoMethodCommand("method param"));
    }
}

当我运行这个测试时,在模块中的DoMethodCommand中执行的所有日志记录都会被记录到测试运行程序中的控制台。

基于API的集成测试

代码语言:javascript
复制
public class Tests
{
    private TestServer _testServer;
    private HttpClient _httpClient;

    [OneTimeSetUp]
    public void SetupTestServerAndHttpClient()
    {
        _testServer = new TestServer(new WebHostBuilder()
            .UseStartup<MyWebAPIProject.Startup>();

        _httpClient = _testServer.CreateClient();
    }

    [Test]
    public async Task TestMyAPIMethod()
    {
        await _httpClient.PostAsync("myapiroute", "method param");
    }
}

MyWebAPIProject.Startup.cs

代码语言:javascript
复制
public void ConfigureServices(IServiceCollection services)
{
    ILogger loggerForModule;

    using (ILoggerFactory loggerFactory.Create(b => 
    {
        b.AddConsole();
        b.AddDebug();
    }))
    {
        loggerForModule = loggerFactory.CreateLogger("Module.Logging")
    }

    ModuleInitializer.Initialize(loggerForModule);
}

使用上面的方法,API将命令传递到我的模块中,一切都会执行,我可以在调试窗口中看到所有模块日志记录,但是在Visual测试运行程序输出中没有任何信息。

EN

回答 1

Stack Overflow用户

发布于 2022-10-23 00:45:41

我也在使用Nunit,我有同样的问题,我在AspNetCore.TestHost: How to get log output from the in-process server?上找到了一个答案

我使用了Serilog.Sinks.InMemory,添加了以下内容:

代码语言:javascript
复制
    public class InMemoryAPIHosting
    {
        public WebApplicationFactory<Startup> API { get; set; }

        public InMemoryAPIHosting()
        {
            API = new APIWebApplicationFactory()
                      .WithWebHostBuilder(builder =>
                      {
                          //This allows us to access Serilog entries created while the API is running during integration tests. We can inspect them using InMemorySink.Instance.LogEvents.
                          builder.UseSerilog((ctx, conf) => conf.WriteTo.InMemory());
                      });
        }

        public void Dispose()
        {
            API.Dispose();
        }
    }

最后,在我的测试方法中,我创建了一个可以像这样调用的方法:

代码语言:javascript
复制
        //Helper method that checks the In Memory API logs and writes it to the test output if it finds any
        public static void CheckSeriLogEvents(bool throwOnError = false)
        {
            //After starting up the in memory API, let's review the log items to see if there are any errors. If so, spit them out into the test output.
            if (InMemorySink.Instance.LogEvents.Any(x => x.Level == Serilog.Events.LogEventLevel.Error))
            {
                //There was an error in the logs of the In Memory API! Spit it out.
                TestLogger.WriteTestOutput("Error in Memory API. Please review the log data.");
                foreach (var logEvent in InMemorySink.Instance.LogEvents.Where(x => x.Level >= Serilog.Events.LogEventLevel.Warning))
                {
                    TestLogger.WriteTestOutput(logEvent.Timestamp + ": " + logEvent.RenderMessage(), false);
                }

                //End the test immediately with an error, if a throw was requested
                if (throwOnError)
                {
                    throw new SerilogInMemoryStartupException("Error in Memory API. Please review the log data. Test aborted.");
                }
            }
        }
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69760212

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档