Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebApplicationFactory error, not throwed in debug mode

I'm using a .NET Nunit project and trying to create a fixture for my integration tests using WebApplicationFactory class

When I run tests I get the exception

System.InvalidOperationException : The server has not been started or no web application was configured.

But, if debug I don't get any error and the tests run without problems. I literally copy pasted a few different good implementations I found online, and also removed every tests configuration or service replacement, and I still get the error.

This is my configuration

public class Initializer
{
    protected WebApplicationFactory<Program> application { get; set; }
    protected HttpClient client { get; set; }

    protected IServiceProvider _serviceProvider;

    [SetUp]
    public void RunBeforeAnyTests()
    {
        application = new WebApplicationFactory<Program>().WithWebHostBuilder(conf =>
        {
            conf.UseEnvironment("Test");
        });

        client = application.Server.CreateClient();
        _serviceProvider = application.Services;
    }

}

I can't investigate because in debug mode I don't have the problem.. I'm stuck on this, anyone can help me?

like image 534
Manuele Occhialini Avatar asked Oct 23 '25 22:10

Manuele Occhialini


1 Answers

I had the exact same error message coming from my tests. In my case, it was an error in the application (web API) itself.

There was an ambiguous route defined, so the application threw an exception and exited.

Unfortunately, when running the test project you don't "see" the exception that the application threw because it's running on a different thread.

From Andrew Lock blog:

_hostStartTcs is a TaskCompletionSource that is used to handle the edge case where the application running in the background exits due to an exception. It's an edge case, but without it, the test could hang indefinitely.

That statement made me realize that the application could just have "crashed", as it turn out it did.

So I would also suggest you try to run your application and do a sanity check that it's not crashing at startup.

like image 167
Pedro Magueija Avatar answered Oct 26 '25 12:10

Pedro Magueija



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!