gpt4 book ai didi

.net-core - 如何使用 xunit 和 moq 传递我的 DbContext 对象进行测试

转载 作者:行者123 更新时间:2023-12-02 19:22:09 25 4
gpt4 key购买 nike

下面提到的是测试函数,用于检查特定 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 是从构造函数注入(inject)的 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 的新手。

请帮我解决这个问题。

提前致谢

最佳答案

所以这里的根本原因是你无法在 Moq 中模拟扩展方法

您在这里执行此操作:

 _serviceScopeFactory.Setup(x => x.CreateScope().ServiceProvider.GetRequiredService<MriDbContext>()).Returns(_context);

GetRequiredService<T>是一个扩展方法,它扩展 IServiceProvider你可以看到here

根据您尝试测试的具体情况(您是在测试上下文创建还是对数据库的实际写入?),您应该能够重新编写测试以避免模拟扩展方法并模拟正在使用的公共(public)实例方法。您甚至可以模拟IServiceProvider上的实际实例方法。如果你真的想保留现有的结构。

存在对此主题的进一步讨论 here 。该问题使用 MSTest 而不是 XUnit,但您此处的问题特定于 Moq。

关于.net-core - 如何使用 xunit 和 moq 传递我的 DbContext 对象进行测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62897718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com