C#C
C#3y ago
Savage

✅ Problems with mocking a ServiceProvider

So, for an integration test I want to create a substitute for the general service provider my application uses.
The service provider is used to create a scope in a constructor/ factory.

This is a minimal code example that showcases the issue:
[Fact]
public void SampleForServideProviderConfiguration()
{
  var serviceProvider = Substitute.For<IServiceProvider>();
  var scopeSubstitute = Substitute.For<IServiceScope>();
  serviceProvider.CreateScope().Returns(scopeSubstitute);
}


On the last line I get the error:

An exception of type 'System.InvalidOperationException' occurred in Microsoft.Extensions.DependencyInjection.Abstractions.dll but was not handled in user code: 'No service for type 'Microsoft.Extensions.DependencyInjection.IServiceScopeFactory' has been registered.'
Was this page helpful?