Reputation: 728
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
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
Reputation: 728
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