codecutout/MockHttpClient

How to use the mock client ?

Closed this issue · 1 comments

Is there a package to install to re-use the mock client implementation ?

MockHttpClient extends HttpClient. So in your test cases rather than passing your subject under a test a real HttpClient you can pass it the MockHttpClient.

Its a little bit contrived but if I was testing a WidgetService I could fake responses in my test cases to prevent making real http calls and making my tests depend on an external service

public class WidgetService
{
    private readonly HttpClient httpClient;

    public WidgetService(HttpClient httpClient)
    {
        this.httpClient = httpClient;
    }

    public async Task<bool> DoesWidgetExist(string widgetId)
    {
        var result = await httpClient.GetAsync($"https://widgetservices.com/widgets/{widgetId}");
        return result.IsSuccessStatusCode;
    }
}

public class WidgetServiceTest
{
    [Fact]
    public async Task When_widget_exists_should_return_true()
    {
        // Arrange
        var client = new MockHttpClient();
        client.When("https://widgetservices.com/widgets/7357").Then(_ => new HttpResponseMessage(System.Net.HttpStatusCode.OK));

        var sut = new WidgetService(client);

        // Act
        var doesExist = await sut.DoesWidgetExist("7357");

        // Assert
        Assert.True(doesExist);

    }

    [Fact]
    public async Task When_widget_not_found_should_return_false()
    {
        // Arrange
        var client = new MockHttpClient();
        client.When("https://widgetservices.com/widgets/7357").Then(_ => new HttpResponseMessage(System.Net.HttpStatusCode.NotFound));

        var sut = new WidgetService(client);

        // Act
        var doesExist = await sut.DoesWidgetExist("7357");

        // Assert
        Assert.False(doesExist);

    }
}