I'm building up some integration tests and I'm using the WebApplicationFactory
class to spin-up an in-memory version of my API.
I'm trying to add some services to my unit tests, and I'm following the guidance in MS docs. Unfortunately, once I try to fetch a required service, I am finding that the services are not registered in the service collection.
I've also tried looking at _apiFactory.Server.Services
but it doesn't seem to contain the services either. Any ideas on this one?
public class MinimumCodeTests: IClassFixture<CustomApiFactory>
{
private readonly CustomApiFactory _apiFactory;
public MinimumCodeTests(CustomApiFactoryapiFactory)
{
_apiFactory = apiFactory;
}
[Fact]
public async Task SampleTest()
{
// Arrange
var httpClient = _apiFactory.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
services.AddScoped<IServiceOne, ServiceOne>(); // Required by ServiceTwo
services.AddScoped<IServiceTwo, ServiceTwo>();
});
}).CreateClient();
var serviceTwo = _apiFactory.Services.GetRequiredService<IServiceTwo>(); // Does not work
}
}
On calling var serviceTwo = _apiFactory.Services.GetRequiredService<IServiceTwo>();
, I get the following error:
System.InvalidOperationException : Cannot resolve scoped service 'DataAccess.Services.IEventService' from root provider.
EDIT: I've omitted some code that shows integration with data access layer/database for simplicity.