Home > Backend Development > C++ > How to Mock HttpClient for Effective Unit Testing?

How to Mock HttpClient for Effective Unit Testing?

Susan Sarandon
Release: 2025-01-13 13:46:43
Original
423 people have browsed it

How to Mock HttpClient for Effective Unit Testing?

Mock HttpClient in unit tests

In unit testing, it is common practice to mock external dependencies to isolate the behavior of the target code. Mock HttpClient allows testing code that relies on HTTP requests without making actual network calls.

Consider the following scenario:

<code class="language-csharp">public interface IHttpHandler
{
    HttpClient Client { get; }
}

public class HttpHandler : IHttpHandler
{
    public HttpClient Client => new HttpClient();
}

public class Connection
{
    private readonly IHttpHandler _httpClient;

    public Connection(IHttpHandler httpClient)
    {
        _httpClient = httpClient;
    }

    public void DoSomething() { /* 使用 _httpClient.Client 进行 HTTP 调用 */ }
}</code>
Copy after login

In a unit test project, you may want to mock the HttpClient to avoid making network calls and focus on testing the logic of the Connection class.

<code class="language-csharp">private IHttpHandler _httpClient;

[TestMethod]
public void TestMockConnection()
{
    //此处需要创建 HttpClient 的模拟实例,而不是真实的实例
    var connection = new Connection(_httpClient);
    connection.DoSomething();
}</code>
Copy after login

To do this, you can use dependency injection to inject a mock HttpClient. The extensibility of HttpClient lies in the HttpMessageHandler passed to the constructor. You can create a mock HttpMessageHandler in your unit test and pass it to the HttpClient constructor.

<code class="language-csharp">[TestMethod]
public void TestMockConnection()
{
    var mockHttp = new MockHttpMessageHandler(); // 创建一个模拟 HttpMessageHandler

    var httpClient = new HttpClient(mockHttp); // 将模拟 HttpMessageHandler 传递给 HttpClient 构造函数

    var connection = new Connection(new HttpHandler { Client = httpClient }); // 将模拟 HttpClient 注入 Connection 类

    connection.DoSomething();

    // 通过对模拟 HttpMessageHandler 设置期望来验证是否进行了预期的 HTTP 请求。
}</code>
Copy after login

By using dependency injection and mocking the HttpMessageHandler, you can effectively isolate the code under test and verify its behavior without making actual network calls.

The above is the detailed content of How to Mock HttpClient for Effective Unit Testing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template