【问题标题】:MSUnit Testing Async HellMSUnit 测试异步地狱
【发布时间】:2017-05-24 21:29:13
【问题描述】:

我有一个async Task 单元测试(MVC、c#、.NET 4.5.2)。它对aysnc Task<ActionResult> 方法执行await,而该方法又对异步方法执行await 调用。

如果我选择它们并从 Visual Studio 2017 的右键菜单中选择 Debug Selected Tests,则测试和其他类似的测试将通过。

问题是当我选择Run Selected TestsRun All 时。如果遵循开头提到的条件,那么许多测试将失败。任何只返回RedirectToRouteResult 而没有进行上述深入研究的测试都将通过。

[TestMethod]
public async Task TestPartsController_GetPartInfo_ReturnsInfo()
{
   //arrange
   PartController pc = new PartController();

   //act
   var result = await pc.GetPartInfo("PC123456");

   //assert
   Assert.IsIntanceOfType(result, typeof(ViewResult));
   Assert.AreEqual("Form", ((ViewResult)result).ViewName);
   Assert.AreEqual("PC123456", result.Model.PartNum.ToUpper());
}

public async Task<ActionResult> GetPartInfo(string partNum)
{
   if (string.IsNullOrEmpty(partNum)
   {
      return RedirectToAction("Index")
   }

   var response = await ServiceClient.GetJsonAsync("/part/partinfo", "?partNum=" + partNum;
   response.EnsureSuccessStatusCode();
   results = await response.Content.ReadAsAsync<Dto.PartNumInfo>();
   ...
   return View("Form", model);
}

public async Task<HttpResponseMessage> GetAsync(Controllers controller, string criteria)
{
   HttpClient client;
   string service = GetService(controller, out client);
   var response = await client.GetAsync(service + criteria);
   return response;
}

解决方案 一直使用 async/await 以及 using statements 和 IDisposable。

 public async Task<HttpResponseMessage> GetJsonAsync<T>(Controllers controller, T data)
 {
    HttpResponseMessage response;

    using (var service = new MyService())
    {
       HttpClient http;
       string serviceLoc = service.GetServiceClient(controller, out http);
       response = await http.GetAsync(serviceLoc, data);
    }

    return response;
}

【问题讨论】:

  • 到那时,许多测试将失败您能否提供一些有关它们如何失败的详细信息?另外,我很难弄清楚if they follow the conditions in the beginning的含义。 条件指的是什么?
  • 他们因无法继续深入了解异步方法而失败。条件就是第一段中提到的。
  • 您应该发布您的解决方案作为答案,而不是对问题的编辑。然后你就可以接受答案了。

标签: c# unit-testing async-await mstest


【解决方案1】:

解决方案一直使用 async/await 以及 using statements 和 IDisposable。

public async Task<HttpResponseMessage> GetJsonAsync<T>(Controllers controller, T data)
{
    HttpResponseMessage response;

    using (var service = new MyService())
    {
       HttpClient http;
       string serviceLoc = service.GetServiceClient(controller, out http);
       response = await http.GetAsync(serviceLoc, data);
    }

    return response;
}

【讨论】:

    猜你喜欢
    • 2011-09-08
    • 2015-01-05
    • 2019-06-21
    • 2017-09-02
    • 2013-11-07
    • 2015-07-11
    • 2018-05-16
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多