Skip to content

dfederm/Testing.HttpClient

Repository files navigation

Testing.HttpClient

NuGet NuGet

Overview

This is a library to help simplify testing the .NET HttpClient. It is heavily influenced by other open source http testing libraries, most notably angular's http/testing.

The library ensures that the HttpClient never hits the network and allows your tests to assert expectations on the requests made through it, validate the requests, and provide mock respones.

Getting started

To use Testing.HttpClient:

  1. Ensure your existing unit test project is targeting a framework that supports netstandard2.0 (eg. .NET Core 2.0+ or .NET Framework 4.6.1+)
  2. Update your unit test's csproj to reference the Testing.HttpClient package:
<PackageReference Include="Testing.HttpClient" Version="1.0.0" />
  1. Use the HttpClientTestingFactory class in your tests to create and configure an HttpClient your code under test can consume.

Example

[TestMethod]
public async Task ExampleTest()
{
    using (var http = new HttpClientTestingFactory())
    {
        var worker = new Worker(http.HttpClient);

        // Make the call, but don't await the task
        var resultTask = worker.FetchDataAsync();

        // Expect the request and respond to it
        var request = http.Expect("http://some-website.com/some-path");
        request.Respond(HttpStatusCode.OK, "123");

        // Await the result and assert on it
        var result = await resultTask;
        Assert.AreEqual(123, result);
    }
}

More code samples.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages