ServiceProviderServiceExtensions.GetRequiredService may not be used in setup and verification expressions

655 Views Asked by At

How to inject dependency for ServiceProvider in xUnit used for injecting cache object.

xUnit gives the below error

ServiceProviderServiceExtensions.GetRequiredService may not be used in setup / verification expressions.
1

There are 1 best solutions below

0
On
  • You need to initialise ServiceCollection() which contains ServiceProvider in constructor and build the service provider for the mock.

   public class UpdateUnitTest()
     {
       public UpdateUnitTest()
        {
       _cacheMock = new Mock<IDistributedCache>();
       var serviceCollection = new ServiceCollection();
       serviceCollection.AddScoped<IDistributedCache>(_ => _cacheMock.Object);

       // Create the ServiceProvider
       var serviceProvider = serviceCollection.BuildServiceProvider();

       // serviceScopeMock will contain my ServiceProvider
       var serviceScopeMock = new Mock<IServiceScope>();
        serviceScopeMock.SetupGet<IServiceProvider>(s => s.ServiceProvider)
       .Returns(serviceProvider);

       var serviceScopeFactoryMock = new Mock<IServiceScopeFactory>();
       serviceScopeFactoryMock.Setup(s => s.CreateScope()).Returns(serviceScopeMock.Object);
       _cacheMock = new Mock<IDistributedCache>();
       _handler = new ClassHandler(
       new Mock<ILogger<ClassHandler>>().Object,
       new OptionsWrapper<CacheOptions>(new CacheOptions()),
       serviceProvider);
        }
    }