Unit Testing

Unit testing code that uses RestClient is trivial - use the UnitTestHandler to fake responses without hitting the network, and the Verify method from DalSoft.RestClient.Testing to assert the results fluently.

[Fact]
public async Task GetUser_ProvidingAValidUserId_ReturnsExpectedUser()
{
    var client = new RestClient("http://test.com", new Config()
        .UseUnitTestHandler(request => new HttpResponseMessage
        {
            Content = new StringContent("{ \"id\": 1, \"username\": \"Bret\" }")
        }));

    await client.Resource("users/1").Get()
        .Verify<HttpResponseMessage>(response => response.IsSuccessStatusCode)
        .Verify<User>(user => user.Username == "Bret");
}

The UnitTestHandler can fake/mock pretty much anything in RestClient - including asserting anything about the request. See UnitTestHandler for detailed info on the handler.

Mocking a RestClient dependency

If your code depends on IRestClientFactory (see IHttpClientFactory) you can provide a mock factory returning a RestClient with faked responses - handy for unit tests and for overriding services in e2e tests.

public class MockRestClientFactory : IRestClientFactory
{
    public RestClient CreateClient()
    {
        return new RestClient
        (
            "http://NotUsedAsMockResponseReturned",
            new Config()
                .UseUnitTestHandler(request => new HttpResponseMessage
                {
                    Content = new StringContent("[{ \"name\": \"Hello World\" }]")
                })
        );
    }

    public RestClient CreateClient(string name)
    {
        return CreateClient();
    }
}

Updated: