gpt4 book ai didi

c# - MSUnit 测试异步 hell

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:27 25 4
gpt4 key购买 nike

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

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

问题是当我选择 Run AllRedirectToRouteResult 时。届时,如果它们遵循开头提到的条件,许多测试将失败。任何只返回 ojit_code 而没有进行上述钻取的测试都将通过。

[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 以及使用语句和 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;
}

最佳答案

解决方案一直使用 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;
}

关于c# - MSUnit 测试异步 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44120668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com