【发布时间】:2014-01-18 12:36:07
【问题描述】:
我正在测试一种用于进行 Web API 调用的服务的方法。如果我还在本地运行 Web 服务(位于解决方案中的另一个项目中),则使用普通的 HttpClient 可以很好地进行单元测试。
但是,当我签入我的更改时,构建服务器将无法访问 Web 服务,因此测试将失败。
我通过创建IHttpClient 接口并实现我在我的应用程序中使用的版本,为我的单元测试设计了一种解决方法。对于单元测试,我使用模拟的异步 post 方法制作了一个完整的模拟版本。这是我遇到问题的地方。我想为这个特定的测试返回一个 OK HttpStatusResult。对于另一个类似的测试,我将返回一个糟糕的结果。
测试将运行但永远不会完成。它挂在等待。我是异步编程、委托和 Moq 本身的新手,我一直在搜索 SO 和谷歌一段时间来学习新事物,但我似乎仍然无法解决这个问题。
这是我要测试的方法:
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.");
}
我做错了什么?
感谢您的帮助。
【问题讨论】:
标签: c# unit-testing asynchronous moq