Skip to content

Faking a Network Exception

Pure Krome edited this page Nov 10, 2016 · 4 revisions

Faking an exception

What: Throwing a network exception when the HttpClient attempts to retrieve some data.

Why: Sometimes a severe network error might occur and an exception could be thrown. This is how you can test for that scenario.

How: Create a fake message handler that will throw an exception.

public class MyService : IMyService
{
    private readonly FakeHttpMessageHandler _messageHandler;

    public MyService(FakeHttpMessageHandler messageHandler = null)
    {
        _messageHandler = messageHandler;
    }

    public async Task<Foo> GetSomeDataAsync()
    {
        HttpResponseMessage message;
        string content;
        using (var httpClient = _messageHandler == null
                 ? new System.Net.Http.HttpClient()
                 : new System.Net.Http.HttpClient(_messageHandler))
        {
            message = await httpClient.GetAsync("http://www.something.com/some/website");
            content = await message.Content.ReadAsStringAsync();
        }
        
        if (message.StatusCode != HttpStatusCode.OK)
        { 
            // TODO: handle this ru-roh-error.
        }
        
        // Assumption: content is in a json format.
        var foo = JsonConvert.DeserializeObject<Foo>(content);
        
        return foo;
    }
}

// ... and a unit test ...

[Fact]
public async Task GivenAValidHttpRequest_GetSomeDataAsync_ReturnsAFoo()
{
    // Arrange.
    const string errorMessage = "Oh man - something bad happened.";
    var expectedException = new HttpRequestException(errorMessage);
    var messageHandler = new FakeHttpMessageHandler(expectedException);
    
    var myService = new MyService(messageHandler);

    // Act.
    // NOTE: network traffic will not leave your computer because you've faked the response, above.
    var exception = await Should.ThrowAsync<HttpRequestException>(async () => await myService.GetSomeDataAsync());
    
    // Assert.
    exception.Message.ShouldBe(errorMessage);
}

Clone this wiki locally