![](/img/trans.png)
[英]Simulating CancellationToken.IsCancellationRequested when unit testing
[英]HTTPClientFactory MOQ testing cancellationToken is true when running in normal, but when executing unit test case cancelation token is false
我正在嘗試使用 IHttpClientFactory 進行 PostAsync 調用,取消令牌工作正常,異常被 CatchBlock 捕獲。
但是當試圖模擬該方法時,Cancellation 標記為 false 並且 catch 塊未被捕獲
以下代碼為 controller 和起訂量 class
值控制器.cs
[Route("[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public ValuesController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[HttpGet]
public async Task<ActionResult> Get()
{
try
{
var client = _httpClientFactory.CreateClient("Test");//Statup register this in startup.cs
/*services.AddHttpClient("Test", httpClient =>{});*/
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string json = JsonConvert.SerializeObject(table);
CancellationTokenSource source = new CancellationTokenSource(1);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", httpContent, source.Token);
//Source.Token is false when running the below MOQ test case
string result = "" + response.Content + " : " + response.StatusCode;
return StatusCode(200, result);
}
catch (OperationCanceledException e)
{
return null;
}
catch (Exception e)
{
return null;
}
}
}
起訂量 Class
單元測試1.cs
public class UnitTest1
{
[Fact]
public void Test1()
{
//Arrange
var mockFactory = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent("{'name':thecodebuzz,'city':'USA'}"),
});
var client = new HttpClient(mockHttpMessageHandler.Object);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
ValuesController controller = new ValuesController(mockFactory.Object);
//Act
var result = controller.Get() ;
//Assert
Assert.NotNull(result);
//Assert.Equal(HttpStatusCode.OK, (HttpStatusCode)result.StatusCode);
}
}
如果您想評估 catch 分支,請設置您的模擬以拋出OperationCanceledException
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ThrowsAsync(new OperationCanceledException(...));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.