[英]Net 5 unit test with multiple using httpClientFactory
這是我僅在嘗試編寫測試時遇到的問題。 在 Net 5 解決方案中,我在 MyController 中測試 GetResult():
public class MyController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
private readonly IConfiguration _config;
public MyController(IHttpClientFactory httpClientFactory, IConfiguration config)
{
_httpClientFactory = httpClientFactory;
_config = config;
}
public async Task<IActionResult> GetResult(int id)
{
var firstResult = await GetFirstResult(id);
var secondResult = await GetSecondResult(id);
return Ok("")
}
private async Task<int> GetFirstResult(int id)
{
using (var httpClient = _httpClientFactory.CreateClient("MySetting"))
{
var response = await httpClient.GetAsync($"MyUrl1{id}");
return (response.IsSuccessStatusCode ? 0 : 1);
}
}
private async Task<int> GetSecondResult(int id)
{
using (var httpClient = _httpClientFactory.CreateClient("MySetting"))
{
var response = await httpClient.GetAsync($"MyUrl2{id}");
return (response.IsSuccessStatusCode ? 0 : 1);
}
}
我的測試:
[Test]
public async Task Get_Should_Return_OK_String()
{
var httpClientFactory = new Mock<IHttpClientFactory>();
var client = new HttpClient();
client.BaseAddress = new Uri("https://sthing/server.php");
httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>))).Returns(client);
var config = InitConfiguration();
var controller = new MyController(httpClientFactory.Object, config);
var result = await controller.GetResult(1);
Assert.NotNull(result);
}
在 return(response...) 行的 GetSecondResult() 中拋出異常。 消息:“無法訪問已處置的 object。Object 名稱:'System.Net.Http.HttpClient'。”
我知道這種情況為什么這個 HttpClient 用法給我一個“無法訪問已處理的 object”。 錯誤? 但是沒有使用 httpClientFactory。 有沒有辦法通過工廠將false傳遞給客戶端的構造函數? 為什么它會在測試中起作用?
首先, .NET 5 今天失去支持。 您應該遷移到當前的長期支持版本 .NET 6。 這不是突然的變化,.NET Core 的生命周期是幾年前宣布的。 大多數情況下,您需要做的就是將項目中的 .net5.0 更改為 .net6.0 並更新 NuGet 個包。
至於錯誤,它是由using
塊引起的:
using (var httpClient = _httpClientFactory.CreateClient("MySetting"))
這不是必需的(實際上是不鼓勵的),HttpClient 實例和 sockets 由 HttpClientFactory 匯集和回收。
測試代碼配置為每次返回相同的 HttpClient 實例:
var client = new HttpClient();
client.BaseAddress = new Uri("https://sthing/server.php");
httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>)))
.Returns(client);
對GetFirstResult()
的調用會處理此實例,任何后續使用都會拋出
要解決此問題,請不要使用using
。 HttpClient 無論如何都應該被重用:
var httpClient = _httpClientFactory.CreateClient("MySetting");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.