LESSON 17 OF 18

17. End-to-End Order Tests from API to Database

Learn how to combine WebApplicationFactory, a real HTTP client, application services, Entity Framework Core, and a SQL Server test database to verify an order workflow end to end.

45 dk 68

Introduction

In the previous lessons, we configured the WebApplicationFactory test host, tested API validation, and connected Entity Framework Core to SQL Server. In this lesson, we will combine those pieces in one realistic scenario: a client will create an order over HTTP, the request will pass through the ASP.NET Core pipeline, the application service will execute business rules, Entity Framework Core will persist the data to a SQL Server test database, and the order will then be queried through HTTP.

This approach verifies a broader behavior than a traditional unit test. Controller execution, model binding, validation, dependency injection, the application service, DbContext, SQL queries, database schema, and JSON serialization participate in the same test flow. These tests do not replace all other tests. Fast unit tests should continue to cover business rules, while a focused set of integration tests should verify important data-access behavior and API contracts.

The goal is not merely to check that the API returns HTTP 201. The goal is to prove that the request was processed correctly, persisted to SQL Server, and can later be read back through the same application.

Scenario and test boundary

Assume that the sample application contains the following components:

  • OrdersController exposes POST /api/orders and GET /api/orders/{id}.
  • OrderApplicationService checks that products exist, calculates the total, and saves the order.
  • ApplicationDbContext manages the Orders and OrderItems tables.
  • The test environment uses an isolated SQL Server test database instead of the normal application database.

We will not run expensive or unstable external dependencies, such as a payment provider or email service, as real services. As covered in earlier lessons, those dependencies can be replaced with test services or mocks. The application’s own HTTP pipeline and SQL Server data access, however, remain real.

Managing the test database connection

Rather than hard-coding a connection string in source code, read it from an environment variable. For example, a local development machine might use the following connection string:

Server=(localdb)\MSSQLLocalDB;Database=Orders_IntegrationTests;Trusted_Connection=True;TrustServerCertificate=True;

In CI, TEST_SQL_CONNECTIONSTRING can point to a temporary SQL Server database created by the pipeline. A test-specific database name prevents accidental deletion of developer data.

Keep the required package versions aligned with the application’s .NET 10 and EF Core versions:

dotnet add package Microsoft.AspNetCore.Mvc.Testing dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package FluentAssertions

The production application will commonly configure its connection string like this:

builder.Services.AddDbContext<ApplicationDbContext>(options =>    options.UseSqlServer(        builder.Configuration.GetConnectionString("DefaultConnection")));

Creating a custom WebApplicationFactory

The test host must replace the application’s database registration after the application startup code has run. Create a custom factory by inheriting from WebApplicationFactory<Program>. The following example reads the connection string from an environment variable and registers ApplicationDbContext with the SQL Server provider:

public sealed class OrdersApiFactory : WebApplicationFactory<Program> {    private readonly string _connectionString =        Environment.GetEnvironmentVariable("TEST_SQL_CONNECTIONSTRING")        ?? throw new InvalidOperationException(            "TEST_SQL_CONNECTIONSTRING is not configured.");    protected override void ConfigureWebHost(IWebHostBuilder builder)    {        builder.UseEnvironment("Testing");        builder.ConfigureServices(services =>        {            var descriptor = services.SingleOrDefault(                service => service.ServiceType ==                    typeof(DbContextOptions<ApplicationDbContext>));            if (descriptor is not null)            {                services.Remove(descriptor);            }            services.AddDbContext<ApplicationDbContext>(options =>                options.UseSqlServer(_connectionString));        });    } }

The important detail is that the original registration is removed and then added again with the test connection. Simply adding a second DbContext configuration can leave multiple registrations in the dependency injection container and make the selected configuration unclear.

Preparing and resetting the database

The database schema must exist before the tests run. If the project uses migrations, call Database.MigrateAsync() during test setup. EnsureCreatedAsync() can also be used for an isolated temporary database, but it does not verify migration behavior.

public sealed class OrdersApiFactory : WebApplicationFactory<Program> {    // ConfigureWebHost is the same as in the previous example.    public async Task ResetDatabaseAsync()    {        await using var scope = Services.CreateAsyncScope();        var db = scope.ServiceProvider            .GetRequiredService<ApplicationDbContext>();        await db.Database.EnsureDeletedAsync();        await db.Database.MigrateAsync();        db.Products.AddRange(            new Product { Id = 101, Name = "Keyboard", Price = 80m },            new Product { Id = 102, Name = "Mouse", Price = 25m });        await db.SaveChangesAsync();    } }

EnsureDeletedAsync must only be used with a database dedicated to testing. If a developer, staging, or production connection string is accidentally supplied, data loss can occur. A safer approach is to validate the database name or use a separate SQL Server instance for integration tests.

Creating an order with a real HTTP client

The test class can use the factory as an xUnit fixture. Reset the database before each test so that tests do not depend on data left by earlier tests:

public sealed class OrderFlowTests : IClassFixture<OrdersApiFactory> {    private readonly OrdersApiFactory _factory;    public OrderFlowTests(OrdersApiFactory factory)    {        _factory = factory;    }    [Fact]    public async Task CreateOrder_then_getOrder_returns_persisted_order()    {        await _factory.ResetDatabaseAsync();        using var client = _factory.CreateClient();        var request = new CreateOrderRequest(            CustomerId: 7,            Items: new[]            {                new CreateOrderItemRequest(ProductId: 101, Quantity: 2),                new CreateOrderItemRequest(ProductId: 102, Quantity: 1)            });        using var createResponse = await client.PostAsJsonAsync(            "/api/orders", request);        createResponse.StatusCode.Should().Be(HttpStatusCode.Created);        var created = await createResponse.Content            .ReadFromJsonAsync<OrderResponse>();        created.Should().NotBeNull();        created!.CustomerId.Should().Be(7);        created.Total.Should().Be(185m);        created.Id.Should().BeGreaterThan(0);        using var getResponse = await client.GetAsync(            $"/api/orders/{created.Id}");        getResponse.StatusCode.Should().Be(HttpStatusCode.OK);        var loaded = await getResponse.Content            .ReadFromJsonAsync<OrderResponse>();        loaded.Should().NotBeNull();        loaded!.Id.Should().Be(created.Id);        loaded.CustomerId.Should().Be(7);        loaded.Total.Should().Be(185m);        loaded.Items.Should().HaveCount(2);    } }

There are two HTTP calls in this test. The first verifies the write behavior, while the second verifies that the data can actually be read back from the database. Checking only the created object is not enough because a controller or service could produce that object without successfully persisting anything. The second GET call proves persistence.

How the request crosses the application layers

The request follows approximately this path inside the application:

  1. The JSON body is converted into a CreateOrderRequest object.
  2. ASP.NET Core validation rules execute.
  3. The controller calls OrderApplicationService.
  4. The service queries products through SQL Server and calculates the total.
  5. ApplicationDbContext saves the order and its items.
  6. The controller returns a 201 response with the new order identifier.
  7. The GET request uses a new request scope and DbContext to query the data again.

This flow is valuable because it tests real application boundaries. It also costs more to diagnose when it fails than a unit test. Instead of creating one enormous scenario, divide the critical behavior into separate tests for successful creation, an unknown product, an empty item list, and a missing order.

Combining HTTP and database assertions

When useful, the test can also verify the database directly through a scoped DbContext. This should complement, not replace, the HTTP GET assertion:

await using var scope = _factory.Services.CreateAsyncScope(); var db = scope.ServiceProvider    .GetRequiredService<ApplicationDbContext>(); var stored = await db.Orders    .Include(order => order.Items)    .SingleAsync(order => order.Id == created.Id); stored.CustomerId.Should().Be(7); stored.Items.Should().HaveCount(2);

The GET call checks the API contract and read pipeline. The direct DbContext query checks that the expected rows were stored in the database. It is not necessary to perform both assertions in every test. Using both in a small number of representative tests can make failures easier to diagnose.

Common mistakes

  • Using the InMemory provider instead of SQL Server: InMemory does not fully represent relational behavior or SQL Server-specific query differences. Use the SQL Server provider when SQL Server behavior matters.
  • Leaving data between tests: If results change when test order changes, the tests are not isolated. Choose a clean database, transaction strategy, or reliable cleanup method for every test.
  • Checking only the status code: A 201 response does not prove that the total or item collection is correct. Assert the response body and the result of a later GET.
  • Using the production connection: Manage the test connection through a separate environment variable and add a safety check.
  • Ignoring parallel execution: Tests that share one database can delete or modify each other’s data when running in parallel. Limit xUnit parallelization or generate a separate database name for each test class.
  • Confusing migrations with EnsureCreated: Use MigrateAsync when migration behavior should be tested. Use EnsureCreatedAsync only when a quick temporary schema is sufficient.

Practice exercise

Complete the following exercise:

  1. Add OrdersApiFactory to the test project and read the test connection from an environment variable.
  2. Write a seed method that inserts at least two products into the test database.
  3. Create an order with HTTP POST and verify the 201 response.
  4. Send an HTTP GET request using the created identifier and verify the order items.
  5. Send a POST request with an unknown product identifier and verify the expected status code and ProblemDetails fields.
  6. Run the test twice in succession and prove that the second run is not affected by data from the first run.

Conclusion

In this lesson, we tested a real order workflow from the API boundary to a SQL Server database. WebApplicationFactory started the application inside a test host, HttpClient represented real HTTP calls, the application service executed business rules, and Entity Framework Core persisted data to SQL Server.

End-to-end integration tests can be slower and more expensive, so their number should remain controlled. In critical user journeys, however, they provide evidence that the application components work together. In the final lesson, we will bring the course together by reviewing the test pyramid, CI execution, coverage reports, and long-term maintenance strategies.

Sources