我正在测试一个进行Web API调用的服务的方法.HttpClient如果我还在本地运行Web服务(位于解决方案中的另一个项目中),则使用正常工作正常进行单元测试.
但是,当我签入我的更改时,构建服务器将无法访问Web服务,因此测试将失败.
我已经为我的单元测试设计了一种方法,通过创建一个IHttpClient接口并实现我在我的应用程序中使用的版本.对于单元测试,我使用模拟的异步post方法创建一个模拟版本.这是我遇到问题的地方.我想HttpStatusResult为这个特定的测试返回一个OK .对于另一个类似的测试,我将返回一个糟糕的结果.
测试将运行但永远不会完成.它挂在等待.我是异步编程,代表和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
}
Run Code Online (Sandbox Code Playgroud)
这是我的单元测试方法:
[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 …Run Code Online (Sandbox Code Playgroud)