ServiceProviderServiceExtensions.GetRequiredService 不得在设置和验证表达式中使用

问题描述 投票:0回答:2

如何在 xUnit 中注入 ServiceProvider 的依赖,用于注入缓存对象。

xUnit 给出以下错误

ServiceProviderServiceExtensions.GetRequiredService may not be used in setup / verification expressions.
mocking xunit verification iserviceprovider
2个回答
0
投票

如果有人需要解决这个问题。您可以使用 GetService 底层方法来代替扩展方法,例如:

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

-1
投票
  • 您需要初始化ServiceCollection(),其中包含 ServiceProvider 在构造函数中并为模拟构建服务提供者。

   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);
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.