Search code examples
asp.net-coreloggingintegration-testingasp.net-core-testhost

AspNetCore.TestHost: How to get log output from the in-process server?


I am using the Microsoft.AspNetCore.TestHost to integration-test my ASP.NET Core web service application.

var testServer = new TestServer(
    new WebHostBuilder()
        .UseStartup<Startup>()
        .UseConfiguration(configuration));
var client = testServer.CreateClient();

This works, but I have a problem: If there's an unexpected error on the server side, it typically just throws "Internal Server Error" and I have to debug to see what it does.

Of course I can improve the error messages from my server, but in addition to that I want to be able to see log output from the server.

Is this possible?

I am thinking that when I create my TestServer object above, perhaps I can inject a log sink such as the one from Serilog.Sinks.InMemory and then inspect the contents of that. The WebHostBuilder has a method ConfigureLogging, but I couldn't figure out how to do what I want.


Solution

  • Sure it's possible :)

    You need the Serilog.AspNetCore nuget package, plus (obviously) Serilog.Sinks.InMemory for the sink.

    var testServer = new TestServer(
        new WebHostBuilder()
            .UseSerilog((ctx, conf) => conf.WriteTo.InMemory()) // That's pretty much it.
            .UseStartup<Startup>()
            .UseConfiguration(cBuilder.Build()));
    
    // Then, in the tests, you can access it like this. But you probably know.
    InMemorySink.Instance
        .Should()
        .HaveMessage(...)
    

    If doesn't work, let me know and I will edit the answer. I tested it, and it works for me.