Mocking and resolving Autofac dependency in integration test in AspNetCore with TestServer

Register the mocked implementation with the container builder for the test using ConfigureTestContainer

//...
.ConfigureServices(services => services.AddAutofac())
.ConfigureTestContainer<ContainerBuilder>(builder => {
    builder.RegisterType<MockEventStoreManager>().As<IEventStoreManager>();
})
//...

This should avoid getting the actual implementation that is added by Startup.ConfigureContainer as

If more than one component exposes the same service, Autofac will use the last registered component as the default provider of that service:

Reference Default Registrations

ConfigureTestContainer is invoked after the Startup.ConfigureContainer so the last registration with the mock would be the default provider of the service.


Adding to Nkosi's excellent answer, I'd like to mention that ConfigureTestContainer does not work with the generic host recommended over the web host by Microsoft as of .NET Core 3.0. There is however a workaround proposed by Alistair Evans from the Autofac team. Unfortunately, it relies on the deprecated IStartupConfigureContainerFilter that has been removed in .NET 5.0.

This means that currently in .NET 5.0 there is no way to mock dependencies injected by an external DI container in integration tests when using the generic host.

Luckily, David Fowler from the ASP.NET team is looking into the issue.