1

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.

sonodan
  • 41
  • 1
  • 6
  • Is it an unit or an integration test? – Peter Csala Mar 31 '23 at 08:39
  • I believe an integration test, as it tests interaction between my API, data access layer and DB. I've left out the call to the API to simplify the code. – sonodan Mar 31 '23 at 10:48
  • You probably need to create a scope. See this answer https://stackoverflow.com/a/75390799/2599508 – John Mar 31 '23 at 10:52
  • @sonodan Then please update your question to provide clarity. (n the question itself you are mentioning unit testing while in the title and in the tags you are using integration testing. – Peter Csala Mar 31 '23 at 11:11
  • can you show CustomApiFactory? I guess its a wrapper for WebApplicationFactory then you could add your services in the override IHost CreateHost(IHostBuilder builder) of CustomApiFactory. Thats similar to what i did and it works. – jeb Mar 31 '23 at 13:31

0 Answers0