我正在测试一种调用Web API的服务方法。如果我在本地运行Web服务(位于解决方案中的另一个项目中),那么使用普通的HttpClient进行单元测试也是可行的。
但是,当我提交更改后,构建服务器将无法访问Web服务,因此测试将失败。
我已经针对我的单元测试设计了一种解决方法,即创建一个IHttpClient接口并实现一个版本,我在我的应用程序中使用该版本。对于单元测试,我制作了一个模拟版本,包括模拟的异步post方法。这就是我的问题所在。我想为这个特定的测试返回一个OK HttpStatusResult。对于另一个类似的测试,我将返回一个坏结果。
测试将运行,但永远不会完成。它停留在等待await时。我还不熟悉异步编程、委托和Moq本身,并且我已经在Stack Overflow和谷歌上搜索了一段时间,学到了新的东西,但仍然无法解决这个问题。
以下是我正在尝试测试的方法:
public async Task<bool> QueueNotificationAsync(IHttpClient client, Email email)
{
// do stuff
try
{
// The test hangs here, never returning
HttpResponseMessage response = await client.PostAsync(uri, content);
// more logic here
}
// more stuff
}
这是我的单元测试方法:
[TestMethod]
public async Task QueueNotificationAsync_Completes_With_ValidEmail()
{
Email email = new Email()
{
FromAddress = "bob@example.com",
ToAddress = "bill@example.com",
CCAddress = "brian@example.com",
BCCAddress = "ben@example.com",
Subject = "Hello",
Body = "Hello World."
};
var mockClient = new Mock<IHttpClient>();
mockClient.Setup(c => c.PostAsync(
It.IsAny<Uri>(),
It.IsAny<HttpContent>()
)).Returns(() => new Task<HttpResponseMessage>(() => new HttpResponseMessage(System.Net.HttpStatusCode.OK)));
bool result = await _notificationRequestService.QueueNotificationAsync(mockClient.Object, email);
Assert.IsTrue(result, "Queue failed.");
}
我做错了什么?
谢谢你的帮助。
ReturnsAsync
的扩展,可以完全做到这一点。 - Stuart Grassie