[C# UnitTest]Mock IHttpClientFactory中生成HttpClient的方法
在撰寫服務時,若有跟外部的資源或Api整合,需要用到HttpClient作互動時
我們通常會使用加入IHttpClientFactory來由底層生成HttpClient,以避免過度使用HttpClient
IHttpClientFactory是可以透過Mock的機制去Setup CreateHttpClient
不過我們HttpClient真的要模擬的是PostAsync的行為,但是卻沒有IHttpClient可以作Mock
網路上查到有另外做一個IHttpClientWrapper,隔離掉HttpClient的實作的方式,但事倍功半
以下 的方法,是最快可以直接Mock掉HttpClient的作法。主要就是透過 Mock
HttpMessageHanlder的方式,詳細寫法範例如下 !
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>()
)
.ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(new MigrateService.PPAMigrateResponse()
{
Status = "success",
Message = "",
Data = new MigrateService.PPAMigrateMemberInfoResponse()
{
member_id =memberId
}
}))
})
.Verifiable();
var mockHttpClient = new HttpClient(handlerMock.Object);
SetupMock<IHttpClientFactory>(a =>
a.Setup(b => b.CreateClient(It.IsAny<string>())).Returns(mockHttpClient));