我正在尝试使用Moq创建一组测试方法,以覆盖外部依赖项。这些依赖在本质上是异步的,我遇到了一组它们,当等待它们时,它们永远不会返回,所以我不知道我缺少了什么。
测试本身非常简单。
[TestMethod]
public async Task UpdateItemAsync()
{
var repository = GetRepository();
var result = await repository.UpdateItemAsync("", new object());
Assert.IsNotNull(result);
}上面的GetRepository方法是用来设置各种模拟对象的,包括在它们上调用的安装程序。
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;
}下面列出了正在测试的代码,当执行带有等待的行时,它永远不会返回。
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;
}我确信错误发生在Setup方法中GetRepository方法中的Moq对象上,但我不知道问题出在哪里。
发布于 2018-05-01 13:28:54
您需要修复异步调用的设置。
Moq有一个ReturnsAsync,它允许模拟的异步方法调用流到完成。
client
.Setup(_ => _.ReplaceDocumentAsync(It.IsAny<Uri>(), It.IsAny<object>(), It.IsAny<RequestOptions>()))
.ReturnsAsync(new ResourceResponse<Document>());您通常希望避免手动更新Task。
https://stackoverflow.com/questions/50117170
复制相似问题