针对异步方法设置 C# 最小起订量测试



我正在尝试使用Moq创建一组测试方法来覆盖外部依赖项。 这些依赖项本质上是异步的,我遇到了一组在等待时永远不会返回的依赖项,所以我不确定我错过了什么。

测试本身非常简单。

[TestMethod]
public async Task UpdateItemAsync()
{
    var repository = GetRepository();
    var result = await repository.UpdateItemAsync("", new object());
    Assert.IsNotNull(result);
}

上面的GetRepository方法是设置各种模拟对象,包括在其上称为 Setup。

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;
}

下面列出了正在测试的代码,当执行带有 await 的行时,它永远不会返回。

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 方法中,但我不确定问题是什么。

您需要修复异步调用的设置

Moq 有一个ReturnsAsync,允许模拟的异步方法调用流向完成。

client
    .Setup(_ => _.ReplaceDocumentAsync(It.IsAny<Uri>(), It.IsAny<object>(), It.IsAny<RequestOptions>()))
    .ReturnsAsync(new ResourceResponse<Document>());

您通常希望避免手动更新Task

最新更新