Dev-lop-er
Dev-lop-er

Reputation: 728

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

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.

Upvotes: 2

Views: 1190

Answers (2)

cowlinb6
cowlinb6

Reputation: 83

In case anyone needs a solution to this. You can use the GetService underlying method instead of the extension method, for example:

var mockServiceScope
  .Setup(c => c.ServiceProvider.GetService(typeof(ITenantLicenceRepository)))
  .Returns(_mockTenantLicenceRepository.Object);

Upvotes: 1

Dev-lop-er
Dev-lop-er

Reputation: 728

  • 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);
        }
    }

Upvotes: -1

Related Questions