Skip to content

Faking a Network Exception

Pure Krome edited this page Dec 23, 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.

[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>(myService.GetSomeDataAsync());
    
    // Assert.
    exception.Message.ShouldBe(errorMessage);
}
Clone this wiki locally