模拟HttpClientFactory以使用Moq框架创建模拟的HttpClient

时间:2019-06-17 13:20:59

标签: c# moq xunit

我有一个方法,其中包含一个创建HttpClientFactory的{​​{1}}。该方法在其中调用HttpClient方法。我需要操纵SendAsync方法来向我发送成功消息,无论它作为参数是什么。

我要测试此方法

SendAsync

我尝试的是

public class TestService
{
    private readonly IHttpClientFactory _clientFactory;

    public TestService(IHttpClientFactory clientFactory)
    {
         _clientFactory = clientFactory;
    }

    public async Task<bool> TestMethod(string testdata)
    {
        var message = new HttpRequestMessage(); //SIMPLIFIED CODE
        var client = _clientFactory.CreateClient();
        var response = await client.SendAsync(message);

        if(response.IsSuccessStatusCode){
            return true;
        }else{
            return false;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我建议看一下Gingster Ale上的以下博客文章。作者的这个示例向您展示了如何模拟对HttpClient的调用:

// ARRANGE
var handlerMock = new Mock<HttpMessageHandler>(MockBehavior.Strict);
handlerMock
   .Protected()
   // Setup the PROTECTED method to mock
   .Setup<Task<HttpResponseMessage>>(
      "SendAsync",
      ItExpr.IsAny<HttpRequestMessage>(),
      ItExpr.IsAny<CancellationToken>()
   )
   // prepare the expected response of the mocked http call
   .ReturnsAsync(new HttpResponseMessage()
   {
      StatusCode = HttpStatusCode.OK,
      Content = new StringContent("[{'id':1,'value':'1'}]"),
   })
   .Verifiable();

// use real http client with mocked handler here
var httpClient = new HttpClient(handlerMock.Object)
{
   BaseAddress = new Uri("http://test.com/"),
};

var subjectUnderTest = new MyTestClass(httpClient);

// ACT
var result = await subjectUnderTest
   .GetSomethingRemoteAsync('api/test/whatever');

// ASSERT
result.Should().NotBeNull(); // this is fluent assertions here...
result.Id.Should().Be(1);

// also check the 'http' call was like we expected it
var expectedUri = new Uri("http://test.com/api/test/whatever");

handlerMock.Protected().Verify(
   "SendAsync",
   Times.Exactly(1), // we expected a single external request
   ItExpr.Is<HttpRequestMessage>(req =>
      req.Method == HttpMethod.Get  // we expected a GET request
      && req.RequestUri == expectedUri // to this uri
   ),
   ItExpr.IsAny<CancellationToken>()
);

此外,如果您可以自由使用HttpClient以外的其他东西,我建议您看看Flurl