E2E Testing

DalSoft.RestClient.Testing makes e2e testing your REST APIs trivial - test real APIs using the fluent Verify method, or test your ASP.NET Core APIs in-memory (no hosting required) using the CreateRestClient extension methods for TestServer and WebApplicationFactory.

E2E testing a real API

Point RestClient at your API and chain Verify calls - a readable e2e test in a couple of lines:

[Fact]
public async Task GetUser_ProvidingAValidUserId_ReturnsExpectedResponse()
{
    var client = new RestClient("https://jsonplaceholder.typicode.com");

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

E2E testing using TestServer

The CreateRestClient extension method turns ASP.NET Core’s in-memory TestServer into a RestClient - meaning you can e2e test your API in-memory using the full power of RestClient and Verify.

[Fact]
public async Task TestServer_VerifyingResponseUsingCreateRestClient_ShouldVerifyResponseAsExpected()
{
    var builder = new WebHostBuilder().UseStartup<Startup>();
    var testServer = new TestServer(builder);
    var client = testServer.CreateRestClient();

    await client.Resource("examples/createclient")
        .Get()
        .Verify<HttpResponseMessage>(response => response.IsSuccessStatusCode)
        .Verify<List<Repository>>(r => r.FirstOrDefault().name != null);
}

E2E testing using WebApplicationFactory

CreateRestClient works with WebApplicationFactory too, including overriding your app’s services to mock dependencies - in this example replacing IRestClientFactory with the MockRestClientFactory from Unit Testing, so the API under test returns a faked downstream response.

public class WebApplicationFactoryTests : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;

    public WebApplicationFactoryTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }

    [Fact]
    public async Task TestServer_VerifyingResponseUsingCreateRestClient_ShouldVerifyResponseAsExpected()
    {
        var client = _factory.WithWebHostBuilder(builder =>
        {
            builder.ConfigureServices(services =>
            {
                services.AddSingleton<IRestClientFactory>(provider => new MockRestClientFactory());
            });
        }).CreateRestClient(new Config());

        await client.Resource("examples/createclient")
            .Get()
            .Verify<HttpResponseMessage>(response => response.IsSuccessStatusCode)
            .Verify<List<Repository>>(repositories => repositories.FirstOrDefault().name == "Hello World");
    }
}

Read Learn How to Test a REST API using C# and DalSoft Rest Client for a full walkthrough.

Updated: