使用Moq针对异步方法设置C#测试 [英] Setting up a C# Test with Moq against Async methods
问题描述
我正在尝试使用Moq创建一组测试方法来覆盖外部依赖项.这些依赖项本质上是异步的,我遇到了一组依赖项,它们在等待时再也不会返回,所以我不确定我缺少了什么.
I'm trying to create a set of test methods using Moq to cover the external dependencies. These dependencies are async in nature and I have come across a set of them that when awaited they never return, so I'm not sure what I'm missing.
测试本身非常简单.
[TestMethod]
public async Task UpdateItemAsync()
{
var repository = GetRepository();
var result = await repository.UpdateItemAsync("", new object());
Assert.IsNotNull(result);
}
上面的 GetRepository
方法是设置各种模拟对象的方法,包括在其上调用安装程序的方法.
The GetRepository
method above is what sets up the various mock objects including called Setup on them.
private static DocumentDbRepository<object> GetRepository()
{
var client = new Mock<IDocumentClient>();
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
client.Setup(m => m.ReplaceDocumentAsync(It.IsAny<Uri>(), It.IsAny<object>(), It.IsAny<RequestOptions>()))
.Returns(() =>
{
return new Task<ResourceResponse<Document>>(() => new ResourceResponse<Document>());
});
var repository = new DocumentDbRepository<object>(configuration, client.Object);
return repository;
}
下面列出了正在测试的代码,当执行带有等待的行时,它永远不会返回.
The code that is under test is listed below and when the line with the await is executed it never returns.
public async Task<T> UpdateItemAsync(string id, T item)
{
var result = await Client.ReplaceDocumentAsync(UriFactory.CreateDocumentUri(DatabaseId, CollectionId, id), item);
return result.Resource as T;
}
我确定错误是在 GetRepository
方法中Moq对象的 Setup
方法中,但是我不确定是什么问题./p>
I'm sure that the error is in the Setup
method on the Moq object in the GetRepository
method, but I'm not sure what the problem is.
推荐答案
您需要修复异步调用中的设置
You need to fix the set up on the async calls
Moq有一个 ReturnsAsync
,它将允许模拟的异步方法调用完成.
Moq has a ReturnsAsync
that would allow the mocked async method calls to flow to completion.
client
.Setup(_ => _.ReplaceDocumentAsync(It.IsAny<Uri>(), It.IsAny<object>(), It.IsAny<RequestOptions>()))
.ReturnsAsync(new ResourceResponse<Document>());
您通常希望避免手动更新 Task
You typically want to avoid newing up Task
s manually
这篇关于使用Moq针对异步方法设置C#测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!