Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TestableHttpClientFactory to support IHttpClientFactory usage #23

Merged
merged 2 commits into from
Aug 15, 2023

Conversation

sandermvanvliet-stack
Copy link
Contributor

This PR adds the TestableHttpClientFactory to help with scenarios where you are using a IHttpClientFactory in your code:

The code under test:

public class TheRealComponent
{
    private readonly IHttpClientFactory _httpClientFactory;

    public TheRealComponent(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    public async Task<string> ExecuteAsync()
    {
        var httpClient = _httpClientFactory.CreateClient("TheNameOfTheClient");
        return await httpClient.GetStringAsync("https://example.com");
    }
}

The test:

var httpClientFactory = new TestableHttpClientFactory();
var handler = httpClientFactory.ConfigureClient("TheNameOfTheClient");

handler
    .RespondTo()
    .Get()
    .ForUrl("https://example.com")
    .With(HttpStatus.OK)
    .AndContent("text/plain", "Hello, world!");

var sut = new TheRealComponent(httpClientFactory);

var result = await sut.ExecuteAsync();

result
    .Should()
    .Be("Hello, world!");

The TestableHttpClientFactory will return a new HttpClient instance which is backed by the TestableMessageHandler you've configured in the test.

@sandermvanvliet sandermvanvliet merged commit 2c6c992 into sandermvanvliet:master Aug 15, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants