RAM
RAM

Reputation: 2759

How to disable services with WebApplicationFactory

I'm adding integration tests to a ASP.NET Core web service (see Microsoft's article on Integration tests in ASP.NET Core and I've extended WebApplicationFactory to replace the Database provider with the in-memory database. However, the ASP.NET Core web service includes other services that are enabled by default.

Each service can be stopped/disabled through the service object, but calls to GetRequiredService() on WebApplicationFactory.ConfigureServices() throw System.InvalidOperationException.

Does anyone know if there is a way to disable default services?

Upvotes: 3

Views: 4269

Answers (2)

Gian Marco
Gian Marco

Reputation: 23199

Just setup your integration test like this:

Try this:

IHostBuilder hostBuilder = // Create from production code
IHost host = await hostBuilder
    .ConfigureWebHost(web => {
        web.UseTestServer();
        web.ConfigureTestServices(svc => {
            svc.RemoveAll<IHostedService>();
        });
    })
    .StartAsync();

HttpClient client = _testHost.GetTestServer().CreateClient();

// Use client to make HTTP requests

Upvotes: 0

Andras
Andras

Reputation: 63

Try this:

var service = services.FirstOrDefault(d => d.ServiceType == typeof(IService));
if (service != null)
{
    services.Remove(service);
}

In your CustomWebApplication factory in the scope of

builder.ConfigureTestServices(services => ...)

Upvotes: 5

Related Questions