如何在 xUnit 中注入 ServiceProvider 的依赖,用于注入缓存对象。
xUnit 给出以下错误
ServiceProviderServiceExtensions.GetRequiredService may not be used in setup / verification expressions.
如果有人需要解决这个问题。您可以使用 GetService 底层方法来代替扩展方法,例如:
var mockServiceScope
.Setup(c => c.ServiceProvider.GetService(typeof(ITenantLicenceRepository)))
.Returns(_mockTenantLicenceRepository.Object);
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);
}
}