【发布时间】:2020-11-03 22:32:50
【问题描述】:
下面提到的是检查特定 transactionId 是否存在详细信息的测试函数。
[Fact]
public async Task GetAllBlobDetails_Test()
{
_serviceScopeFactory.Setup(x => x.CreateScope().ServiceProvider.GetRequiredService<MriDbContext>()).Returns(_context);
BlobStatusEntity blobStatusEntity = await _bspRepository.GetBlobDetails("123");
Assert.NotNull(blobStatusEntity)
}
_serviceScopeFactory 在哪里
Mock<IServiceScopeFactory> _serviceScopeFactory = new Mock<IServiceScopeFactory>();
(Microsoft.Extensions.DependencyInjection)
在上述函数中,它为特定的 transactionId ("123") 调用 _bspRepository.GetBlobDetails
这里是 GetBlobDetails 的定义
public async Task<BlobStatusEntity> GetBlobDetails(string transactionId)
{
if (String.IsNullOrEmpty(transactionId))
{
throw new ArgumentNullException(nameof(transactionId));
}
MriDbContext mriDbcontext = _scopeFactory.CreateScope().ServiceProvider.GetRequiredService<MriDbContext>();
return await mriDbContext.BlobStatus.FirstOrDefaultAsync(ele => ele.TransactionId == transactionId);
}
其中 _scopeFactory 是从构造函数注入的IServiceScopeFactory _scopeFactory。
当我运行上述测试函数 GetAllBlobDetails_Test 时,我收到如下错误。
Message:
System.NotSupportedException : Unsupported expression: ... => ....GetRequiredService<MriDbContext>()
Extension methods (here: ServiceProviderServiceExtensions.GetRequiredService) may not be used in setup / verification expressions.
我是 moq 和 xunit 的新手。
请帮我解决这个问题。
提前致谢
【问题讨论】:
-
在测试代码中,我使用的是内存数据库,并创建了与内存数据库链接的上下文,而不是使用真实数据库。