Scenario: testing with the in-memory harness

Test endpoints the way callers reach them, through a gateway, without a network, a token issuer or a second process. The local in-memory harness runs a gateway in the test process and connects the service to it over the InMemory transport.

The worked example is a test project with four xUnit tests of the billing endpoints from Getting started; it references the billing service project, and its complete test class closes this page. Before each release, an automated run executes them and requires every test to pass.

When to use it

TestUse
One endpoint class, its logic onlyA plain unit test that calls HandleAsync
The endpoint as callers see it: binding, status codes, JSON, routingThe in-memory harness
Authentication, claims, transports, several processesA test environment with a real gateway (Router gateway host)

Packages

The test project references the service project, so its endpoint classes run in the test, and these packages:

<PackageReference Include="StellaOps.Router.Gateway" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Router.Gateway.LocalInMemoryHarness" Version="$(RouterPackageVersion)" />
<PackageReference Include="StellaOps.Router.Transport.InMemory" Version="$(RouterPackageVersion)" />

It also needs <FrameworkReference Include="Microsoft.AspNetCore.App" /> for the gateway, and a test framework (the sample uses xUnit v3).

StellaOps.Router.Gateway and StellaOps.Router.Gateway.LocalInMemoryHarness are under the Router licence; StellaOps.Router.Transport.InMemory is Apache-2.0 (Router packages, Router licence).

The gateway in the test

The harness runs the core gateway pipeline (AddRouterGateway, UseRouterGateway) with the InMemory transport. It refuses to start outside the Development, Testing and Local environments:

// The gateway: the core gateway pipeline with the local in-memory harness. The harness runs only
// in the Development, Testing or Local environment.
var gatewayBuilder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Testing" });
gatewayBuilder.WebHost.UseUrls("http://127.0.0.1:0");
gatewayBuilder.Configuration["GatewayNode:Region"] = "test";
gatewayBuilder.Services.AddSingleton(_registry);
gatewayBuilder.Services.AddRouterGateway(gatewayBuilder.Configuration);
gatewayBuilder.Services.AddRouterGatewayLocalInMemoryHarness(gatewayBuilder.Environment);

_gateway = gatewayBuilder.Build();
_gateway.UseRouterGateway();
await _gateway.StartAsync();
_http = new HttpClient { BaseAddress = new Uri(_gateway.Urls.Single()) };

The service in the test

The service shares the gateway’s InMemoryConnectionRegistry and uses the InMemory transport client. Register the endpoint classes under test, and wait until the gateway lists the endpoint:

// The service: the billing endpoint classes on the InMemory transport client.
var serviceBuilder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
serviceBuilder.Services.AddLogging();
serviceBuilder.Services.AddSingleton(_registry);
serviceBuilder.Services.AddStellaMicroservice(options =>
{
    options.ServiceName = "billing";
    options.Version = "1.0.0";
    options.Region = "test";
    options.InstanceId = "billing-test";
    options.Routers = [new RouterEndpointConfig { Host = "localhost", Port = 1, TransportType = TransportType.InMemory }];
});
serviceBuilder.Services.AddInMemoryTransportClient();
serviceBuilder.Services.AddScoped<CreateInvoiceEndpoint>();
serviceBuilder.Services.AddScoped<GetInvoiceEndpoint>();

_service = serviceBuilder.Build();
await _service.StartAsync();
await WaitForEndpointAsync("GET", "/invoices/{id}");
// The service connects in the background after it starts: wait until the gateway lists the endpoint.
private async Task WaitForEndpointAsync(string method, string path)
{
    var deadline = DateTime.UtcNow.AddSeconds(30);
    while (_registry.GetConnectionsFor("billing", "1.0.0", method, path).Count == 0)
    {
        Assert.True(DateTime.UtcNow < deadline, $"the gateway did not list {method} {path} within 30 seconds");
        await Task.Delay(100);
    }
}

The tests

[Fact]
public async Task CreatingAnInvoiceReturnsADraft()
{
    using var response = await _http!.PostAsJsonAsync(
        "/invoices",
        new { customerId = "CUST-001", amount = 99.99m },
        TestContext.Current.CancellationToken);

    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
    Assert.Equal("draft", body.RootElement.GetProperty("status").GetString());
    Assert.StartsWith("INV-", body.RootElement.GetProperty("invoiceId").GetString());
}

[Fact]
public async Task ReadingAnInvoiceTakesTheIdFromThePath()
{
    using var response = await _http!.GetAsync("/invoices/INV-042", TestContext.Current.CancellationToken);

    Assert.Equal(HttpStatusCode.OK, response.StatusCode);
    using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
    Assert.Equal("INV-042", body.RootElement.GetProperty("invoiceId").GetString());
}

[Fact]
public async Task AnInvalidBodyIsABadRequest()
{
    using var content = new StringContent("{ not json", System.Text.Encoding.UTF8, "application/json");
    using var response = await _http!.PostAsync("/invoices", content, TestContext.Current.CancellationToken);

    Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
}

[Fact]
public async Task AnUnknownPathIsNotFound()
{
    using var response = await _http!.GetAsync("/payments/1", TestContext.Current.CancellationToken);

    Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
}

Run them in the test project’s directory:

dotnet test

Expected result: Passed: 4, Failed: 0.

The complete test class

using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Examples.Billing.Microservice.Endpoints;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using StellaOps.Microservice;
using StellaOps.Router.Common.Enums;
using StellaOps.Router.Gateway;
using StellaOps.Router.Gateway.DependencyInjection;
using StellaOps.Router.Transport.InMemory;
using Xunit;

namespace Examples.Router.Tests;

/// <summary>
/// The billing endpoints, called over HTTP through a gateway that runs in the test process. The
/// gateway and the service share one InMemoryConnectionRegistry, which stands in for the network.
/// </summary>
public sealed class BillingEndpointTests : IAsyncLifetime
{
    private readonly InMemoryConnectionRegistry _registry = new();
    private WebApplication? _gateway;
    private IHost? _service;
    private HttpClient? _http;

    public async ValueTask InitializeAsync()
    {
        // The gateway: the core gateway pipeline with the local in-memory harness. The harness runs only
        // in the Development, Testing or Local environment.
        var gatewayBuilder = WebApplication.CreateBuilder(new WebApplicationOptions { EnvironmentName = "Testing" });
        gatewayBuilder.WebHost.UseUrls("http://127.0.0.1:0");
        gatewayBuilder.Configuration["GatewayNode:Region"] = "test";
        gatewayBuilder.Services.AddSingleton(_registry);
        gatewayBuilder.Services.AddRouterGateway(gatewayBuilder.Configuration);
        gatewayBuilder.Services.AddRouterGatewayLocalInMemoryHarness(gatewayBuilder.Environment);

        _gateway = gatewayBuilder.Build();
        _gateway.UseRouterGateway();
        await _gateway.StartAsync();
        _http = new HttpClient { BaseAddress = new Uri(_gateway.Urls.Single()) };

        // The service: the billing endpoint classes on the InMemory transport client.
        var serviceBuilder = Host.CreateApplicationBuilder(new HostApplicationBuilderSettings { DisableDefaults = true });
        serviceBuilder.Services.AddLogging();
        serviceBuilder.Services.AddSingleton(_registry);
        serviceBuilder.Services.AddStellaMicroservice(options =>
        {
            options.ServiceName = "billing";
            options.Version = "1.0.0";
            options.Region = "test";
            options.InstanceId = "billing-test";
            options.Routers = [new RouterEndpointConfig { Host = "localhost", Port = 1, TransportType = TransportType.InMemory }];
        });
        serviceBuilder.Services.AddInMemoryTransportClient();
        serviceBuilder.Services.AddScoped<CreateInvoiceEndpoint>();
        serviceBuilder.Services.AddScoped<GetInvoiceEndpoint>();

        _service = serviceBuilder.Build();
        await _service.StartAsync();
        await WaitForEndpointAsync("GET", "/invoices/{id}");
    }

    [Fact]
    public async Task CreatingAnInvoiceReturnsADraft()
    {
        using var response = await _http!.PostAsJsonAsync(
            "/invoices",
            new { customerId = "CUST-001", amount = 99.99m },
            TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
        Assert.Equal("draft", body.RootElement.GetProperty("status").GetString());
        Assert.StartsWith("INV-", body.RootElement.GetProperty("invoiceId").GetString());
    }

    [Fact]
    public async Task ReadingAnInvoiceTakesTheIdFromThePath()
    {
        using var response = await _http!.GetAsync("/invoices/INV-042", TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(TestContext.Current.CancellationToken));
        Assert.Equal("INV-042", body.RootElement.GetProperty("invoiceId").GetString());
    }

    [Fact]
    public async Task AnInvalidBodyIsABadRequest()
    {
        using var content = new StringContent("{ not json", System.Text.Encoding.UTF8, "application/json");
        using var response = await _http!.PostAsync("/invoices", content, TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }

    [Fact]
    public async Task AnUnknownPathIsNotFound()
    {
        using var response = await _http!.GetAsync("/payments/1", TestContext.Current.CancellationToken);

        Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
    }

    public async ValueTask DisposeAsync()
    {
        _http?.Dispose();
        if (_service is not null)
        {
            await _service.StopAsync();
            _service.Dispose();
        }

        if (_gateway is not null)
        {
            await _gateway.StopAsync();
            await _gateway.DisposeAsync();
        }
    }

    // The service connects in the background after it starts: wait until the gateway lists the endpoint.
    private async Task WaitForEndpointAsync(string method, string path)
    {
        var deadline = DateTime.UtcNow.AddSeconds(30);
        while (_registry.GetConnectionsFor("billing", "1.0.0", method, path).Count == 0)
        {
            Assert.True(DateTime.UtcNow < deadline, $"the gateway did not list {method} {path} within 30 seconds");
            await Task.Delay(100);
        }
    }
}

What the harness does not test

Pitfalls