我正在尝试为IServiceProvider
创建一个Mock(使用Moq),以便我可以测试我的存储库类:
public class ApiResourceRepository : IApiResourceRepository
{
private readonly IServiceProvider _serviceProvider;
public ApiResourceRepository(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
_dbSettings = dbSettings;
}
public async Task<ApiResource> Get(int id)
{
ApiResource result;
using (var serviceScope = _serviceProvider.
GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
result = await
context.ApiResources
.Include(x => x.Scopes)
.Include(x => x.UserClaims)
.FirstOrDefaultAsync(x => x.Id == id);
}
return result;
}
}
我创建Mock对象的尝试如下:
Mock<IServiceProvider> serviceProvider = new Mock<IServiceProvider>();
serviceProvider.Setup(x => x.GetRequiredService<ConfigurationDbContext>())
.Returns(new ConfigurationDbContext(Options, StoreOptions));
Mock<IServiceScope> serviceScope = new Mock<IServiceScope>();
serviceScope.Setup(x => x.ServiceProvider).Returns(serviceProvider.Object);
serviceProvider.Setup(x => x.CreateScope()).Returns(serviceScope.Object);
我收到以下错误:
System.NotSupportedException:Expression引用一个方法 不属于模拟对象:x =&gt; x.GetRequiredService()
答案 0 :(得分:20)
如前所述,Moq不允许设置扩展方法。
在这种情况下,所述扩展方法的源代码可在Github上获得
ServiceProviderServiceExtensions
解决这类问题的常用方法是找出扩展方法的作用,并通过它的执行安全地模拟路径。
所有这些中的基本类型是IServiceProvider
及其object Getservice(Type type)
方法。此方法是解析服务类型时最终调用的方法。而且我们只处理抽象(接口),这使得使用moq变得更加容易。
//Arrange
var serviceProvider = new Mock<IServiceProvider>();
serviceProvider
.Setup(x => x.GetService(typeof(ConfigurationDbContext)))
.Returns(new ConfigurationDbContext(Options, StoreOptions));
var serviceScope = new Mock<IServiceScope>();
serviceScope.Setup(x => x.ServiceProvider).Returns(serviceProvider.Object);
var serviceScopeFactory = new Mock<IServiceScopeFactory>();
serviceScopeFactory
.Setup(x => x.CreateScope())
.Returns(serviceScope.Object);
serviceProvider
.Setup(x => x.GetService(typeof(IServiceScopeFactory)))
.Returns(serviceScopeFactory.Object);
var sut = new ApiResourceRepository(serviceProvider.Object);
//Act
var actual = sut.Get(myIntValue);
//Asssert
//...
回顾上面的代码,你会看到这种安排如何满足扩展方法的预期行为,并通过扩展(没有双关语)测试方法。
答案 1 :(得分:6)
一般规则是不要模拟不属于您的类型。除非您需要验证对服务提供商的调用,否则只需在测试中从 IServiceProvider
构建 ServiceCollection
。
答案 2 :(得分:1)
我也在寻找这个,但我只需要模拟GetService。我总是使用AutoFac来自动生成模拟。在此示例中,“GetService”始终返回模拟的实例。您可以使用冻结方法更改模拟行为。
示例:强>
要测试的课程:
public class ApiResourceRepository : ApiResourceRepository {
private readonly IServiceProvider _serviceProvider;
public ApiResourceRepository(IServiceProvider serviceProvider) {
_serviceProvider = serviceProvider;
}
public object Get(int id) {
using (var serviceScope = _serviceProvider.CreateScope()) {
var repo = serviceScope.ServiceProvider.GetService<IPersonRepository>();
return repo.GetById(id);
}
}
}
单元测试:
[Fact]
public void Test() {
// arrange
var fixture = new Fixture()
.Customize(new AutoMoqCustomization())
.Customize(new ServiceProviderCustomization());
fixture.Freeze<Mock<IPersonRepository>>()
.Setup(m => m.GetById(It.IsAny<int>()))
.Returns(new Person(Name = "John"));
// Act
var apiResource = _fixture.Create<ApiResourceRepository>();
var person = apiResource.Get(1);
// Assert
...
}
自定义AutoFac提供程序
public class ServiceProviderCustomization : ICustomization {
public void Customize(IFixture fixture) {
var serviceProviderMock = fixture.Freeze<Mock<IServiceProvider>>();
// GetService
serviceProviderMock
.Setup(m => m.GetService(It.IsAny<Type>()))
.Returns((Type type) => {
var mockType = typeof(Mock<>).MakeGenericType(type);
var mock = fixture.Create(mockType, new SpecimenContext(fixture)) as Mock;
// Inject mock again, so the behavior can be changed with _fixture.Freeze()
MethodInfo method = typeof(FixtureRegistrar).GetMethod("Inject");
MethodInfo genericMethod = method.MakeGenericMethod(mockType);
genericMethod.Invoke(null, new object[] { fixture, mock });
return mock.Object;
});
// Scoped
var serviceScopeMock = fixture.Freeze<Mock<IServiceScope>>();
serviceProviderMock
.As<IServiceScopeFactory>()
.Setup(m => m.CreateScope())
.Returns(serviceScopeMock.Object);
serviceProviderMock.As<ISupportRequiredService>()
.Setup(m => m.GetRequiredService(typeof(IServiceScopeFactory)))
.Returns(serviceProviderMock.Object);
}
}
答案 3 :(得分:1)
我想说的是,当您需要添加这么多的仪式来模拟一个简单的方法时,那么您的代码可能就不是很可测试了。因此,另一种选择是将服务定位器隐藏在更具测试性和模拟友好性的界面(我认为也是更好的界面)之后:
public interface IServiceLocator : IDisposable
{
T Get<T>();
}
public class ScopedServiceLocator : IServiceLocator
{
private readonly IServiceScopeFactory _factory;
private IServiceScope _scope;
public ScopedServiceLocator(IServiceScopeFactory factory)
{
_factory = factory;
}
public T Get<T>()
{
if (_scope == null)
_scope = _factory.CreateScope();
return _scope.ServiceProvider.GetService<T>();
}
public void Dispose()
{
_scope?.Dispose();
_scope = null;
}
}
我在这里仅实现了GetService<T>
方法,但是您可以轻松地添加/删除方法,以便定位器更好地满足您的需求。
以及如何使用它的示例;
public class ALongRunningTask : IRunForALongTime
{
private readonly IServiceLocator _serviceLocator;
public ALongRunningTask(IServiceLocator serviceLocator)
{
_serviceLocator = serviceLocator;
}
public void Run()
{
using (_serviceLocator)
{
var repository = _serviceLocator.Get<IRepository>();
}
}
}
答案 4 :(得分:0)
免责声明:嵌入式链接指向我的GitHub和NuGet页面的子页面。但我希望它能对您或其他人有所帮助。
我之所以创造这样的东西,是因为我找不到任何东西。它实现IServiceCollection和IServiceProvider来测试我的启动配置,尤其是是否所有类型都已正确注册到DI容器。它是这些接口的通用替代品,为每个注册类型提供Mocks(Moq)作为单例。 Foo
在GitHub上有一个readme.md,代码库也不是很大。
还有一个nuget package called MockProvider和-如前所述-code is on GitHub。我将其置于MIT之下,因此您可以根据自己的意愿进行操作。它是免费使用和贡献的。
考虑它是一种回馈方式。
答案 5 :(得分:0)
我使用 Moq 和 xUnit 进行测试。我以前遇到过类似的问题,我的解决方案是将数据事务提取到带有接口的 SqlExecuter 类中,以便我可以直接模拟来自数据库的响应。这简化了一切,足以构建服务提供者并将其传入。您将需要 xUnit、Moq 和一些 Microsoft 包(Microsoft.EntityFrameworkCore 和 Microsoft.EntityFrameworkCore.InMemory)。
SqlExecuter.cs
public interface ISqlExecuter
{
Task<List<SqlParameter>> FirstOrDefaultApiResource(ConfigurationDbContext context, int id);
}
public class SqlExecuter : ISqlExecuter
{
public async Task<ApiResource> FirstOrDefaultApiResource(ConfigurationDbContext context, int id) =>
return await context.ApiResources
.Include(x => x.Scopes)
.Include(x => x.UserClaims)
.FirstOrDefaultAsync(x => x.Id == id);
}
ApiResourceRepository.cs
public class ApiResourceRepository : IApiResourceRepository
{
private readonly IServiceProvider _serviceProvider;
private readonly ISqlExecuter _sqlExecuter;
public ApiResourceRepository(IServiceProvider serviceProvider, ISqlExecuter sqlExecuter)
{
_serviceProvider = serviceProvider;
_sqlExecuter = sqlExecuter;
_dbSettings = dbSettings;
}
public async Task<ApiResource> Get(int id)
{
ApiResource result;
using (var serviceScope = _serviceProvider.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<ConfigurationDbContext>();
result = await _sqlExecuter.FirstOrDefaultApiResource(context, id);
}
return result;
}
}
ApiResourceRepositoryTests.cs
[Fact]
public async Task Get_Success()
{
// Arrange
var id = 42069;
var scope = "Scope";
var claim = "UserClaims";
var services = new ServiceCollection();
services.AddDbContext<ConfigurationDbContext>(opt => opt
.UseInMemoryDatabase(databaseName: $"ConfigurationDbContext-{ DateTime.Now.ToString() }")
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)),
ServiceLifetime.Singleton, ServiceLifetime.Singleton);
var serviceProvider = services.BuildServiceProvider();
var mockSqlExecuter = new Mock<SqlExecuter>();
mockSqlExecuter.Setup(x => x.FirstOrDefaultApiResource(It.IsAny<ConfigurationDbContext>(), It.IsAny<int>()))
.Returns(new ApiResource() { Id = id , Scope = scope, UserClaims = claim })
var mockApiResourceRepository = new Mock<ApiResourceRepository>(serviceProvider, mockSqlExecuter.Object);
// Act
var result = await mockApiResourceRepository.Object.Get(id);
// Assert
Assert.NotNull(response);
Assert.Equal(id, result.Id);
Assert.Equal(scope, result.Scope);
Assert.Equal(claim, result.UserClaims);
}
或者,在其他情况下,我不使用 SqlExecuter 类,而是在服务提供者中设置上下文。
// Arrange
var id = 42069;
var scope = "Scope";
var claim = "UserClaims";
var services = new ServiceCollection();
services.AddDbContext<ConfigurationDbContext>(opt => opt
.UseInMemoryDatabase(databaseName: $"ConfigurationDbContext-{DateTime.Now.ToString()}")
.ConfigureWarnings(x => x.Ignore(InMemoryEventId.TransactionIgnoredWarning)),
ServiceLifetime.Singleton, ServiceLifetime.Singleton);
var serviceProvider = services.BuildServiceProvider();
var context = Interfaces.ServiceProvider.GetService<ComQueMDSContext>();
context.ApiResources.RemoveRange(context.ApiResources);
context.ApiResources.AddRange(new List<ApiResource>(){ new ApiResource(){ Id = id, Scope = scope, UserClaims = claim } });
context.SaveChanges();
var mockApiResourceRepository = new Mock<ApiResourceRepository>(serviceProvider);
我还按照 xUnit 的建议将大部分工作提取到了 Fixture 类和集合中,以集中上下文并减少测试时间。
答案 6 :(得分:0)
以防万一它对某人有用,这里有一个示例,说明我如何按照建议的 here 为我的单元测试创建自己的 ServiceProvider。我还添加了 ServiceScope 和 ServiceScopeFactory 模拟来提供所有服务。
这是我的单元测试中的代码:
var serviceCollection = new ServiceCollection();
// Add any DI stuff here:
serviceCollection.AddSingleton<ILogger>(loggerMock.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);
// serviceScopeFactoryMock will contain my serviceScopeMock
var serviceScopeFactoryMock = new Mock<IServiceScopeFactory>();
serviceScopeFactoryMock.Setup(s => s.CreateScope())
.Returns(serviceScopeMock.Object);
然后我可以将我的 serviceScopeFactoryMock 传递给我的 sut 构造函数。
这是正在测试的代码:
using (var scope = _serviceScopeFactory.CreateScope())
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger>();
...
}