模拟 HttpClient 使用 Moq

Mock HttpClient using Moq

提问人:Amitava Karan 提问时间:6/23/2017 最后编辑:Aamir JamalAmitava Karan 更新时间:6/22/2022 访问量:37538

问:

我想对一个使用 .我们在类构造函数中注入了对象。HttpClientHttpClient

public class ClassA : IClassA
{
    private readonly HttpClient _httpClient;

    public ClassA(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<HttpResponseMessage> SendRequest(SomeObject someObject)
    {
        //Do some stuff

        var request = new HttpRequestMessage(HttpMethod.Post, "http://some-domain.in");

        //Build the request

        var response = await _httpClient.SendAsync(request);

        return response;
    }
}

现在我们想对该方法进行单元测试。我们用于单元测试框架和模拟。ClassA.SendRequestMs TestMoq

当我们试图嘲笑 时,它会抛出 .HttpClientNotSupportedException

[TestMethod]
public async Task SendRequestAsync_Test()
{
    var mockHttpClient = new Mock<HttpClient>();

    mockHttpClient.Setup(
        m => m.SendAsync(It.IsAny<HttpRequestMessage>()))
    .Returns(() => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
}

我们该如何解决这个问题?

C# 单元测试 最小起订量 mstest dotnet-httpclient

评论


答:

26赞 Nkosi 6/23/2017 #1

该特定的重载方法不是虚拟的,因此无法被 Moq 覆盖。

public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request);

这就是为什么它抛出NotSupportedException

你要找的虚拟方法就是这个方法

public virtual Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken);

然而,模拟并不像其内部消息处理程序看起来那么简单。HttpClient

我建议使用带有自定义消息处理程序存根的具体客户端,这将在伪造请求时提供更大的灵活性。

下面是委派处理程序存根的示例。

public class DelegatingHandlerStub : DelegatingHandler {
    private readonly Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> _handlerFunc;
    public DelegatingHandlerStub() {
        _handlerFunc = (request, cancellationToken) => Task.FromResult(request.CreateResponse(HttpStatusCode.OK));
    }

    public DelegatingHandlerStub(Func<HttpRequestMessage, CancellationToken, Task<HttpResponseMessage>> handlerFunc) {
        _handlerFunc = handlerFunc;
    }

    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) {
        return _handlerFunc(request, cancellationToken);
    }
}

请注意,默认构造函数基本上是在执行您之前尝试模拟的操作。它还允许使用请求的委托进行更多自定义方案。

使用存根,可以将测试重构为类似

public async Task _SendRequestAsync_Test() {
    //Arrange           
    var handlerStub = new DelegatingHandlerStub();
    var client = new HttpClient(handlerStub);
    var sut = new ClassA(client);
    var obj = new SomeObject() {
        //Populate
    };

    //Act
    var response = await sut.SendRequest(obj);

    //Assert
    Assert.IsNotNull(response);
    Assert.IsTrue(response.IsSuccessStatusCode);
}
8赞 alastairtree 12/6/2017 #2

使用 HttpClient 进行 propper 模拟是一项艰巨的工作,因为它是在大多数人在 dotnet 中进行单元测试之前编写的。有时我会设置一个存根 HTTP 服务器,它根据与请求 url 匹配的模式返回预制响应,这意味着您测试真正的 HTTP 请求不是模拟,而是 localhost 服务器。使用 WireMock.net 使这变得非常容易,并且运行速度足够快,可以满足我的大部分单元测试需求。

因此,不要在某些端口上使用 localhost 服务器设置,然后:http://some-domain.in

var server = FluentMockServer.Start(/*server and port can be setup here*/);
server.Given(
      Request.Create()
      .WithPath("/").UsingPost()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );

您可以在此处找到有关在测试中使用 wiremock 的更多详细信息和指南。

12赞 carlin.scott 4/3/2020 #3

Moq 可以模拟受保护的方法,例如 HttpMessageHandler 上的 SendAsync,您可以在其构造函数中提供给 HttpClient。

var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler.Protected()
    .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
    .ReturnsAsync(new HttpResponseMessage
    {
        StatusCode = HttpStatusCode.OK
     });

var client = new HttpClient(mockHttpMessageHandler.Object);

https://www.thecodebuzz.com/unit-test-mock-httpclientfactory-moq-net-core/ 复制

10赞 kiddagger 3/16/2021 #4

我最近不得不模拟 HttpClient,我使用了 Moq.Contrib.HttpClient。这是我需要的,而且使用简单,所以我想我会把它扔在那里。

以下是一般用法的示例:

// All requests made with HttpClient go through its handler's SendAsync() which we mock
var handler = new Mock<HttpMessageHandler>();
var client = handler.CreateClient();

// A simple example that returns 404 for any request
handler.SetupAnyRequest()
    .ReturnsResponse(HttpStatusCode.NotFound);

// Match GET requests to an endpoint that returns json (defaults to 200 OK)
handler.SetupRequest(HttpMethod.Get, "https://example.com/api/stuff")
    .ReturnsResponse(JsonConvert.SerializeObject(model), "application/json");

// Setting additional headers on the response using the optional configure action
handler.SetupRequest("https://example.com/api/stuff")
    .ReturnsResponse(bytes, configure: response =>
    {
        response.Content.Headers.LastModified = new DateTime(2018, 3, 9);
    })
    .Verifiable(); // Naturally we can use Moq methods as well

// Verify methods are provided matching the setup helpers
handler.VerifyAnyRequest(Times.Exactly(3));

有关更多信息,请在此处查看作者的博客文章。

评论

0赞 Søren 2/17/2023
了不起!在多请求-响应方案中帮助我 - .NET 6.0