ASP.NET Core Integration Testing with a Real Database

ASP.NET Core Integration Testing with a Real Database
```html

Why ASP.NET Core Integration Tests Matter

Unit tests are extremely useful for validating business logic, but a real ASP.NET Core application consists of much more than isolated C# methods.

When an HTTP request enters the system, many components may participate:

  • Routing
  • Middleware
  • Authentication and authorization
  • Dependency injection
  • Controllers or Minimal API endpoints
  • Application services
  • Entity Framework Core
  • SQL Server
  • Transactions and database constraints

Testing each component individually is useful. The more important question, however, is:

“Does the system still behave correctly when all of these components work together?”

That is the purpose of integration testing.

With ASP.NET Core integration tests, we can start the application using a test host, send real HTTP requests through the application pipeline and verify the resulting state in a real database.

1. Unit Tests vs Integration Tests

A unit test normally isolates a single class or method from its dependencies.

OrderService
    ↓
Mock Repository
    ↓
Expected Result

An integration test validates multiple real components together:

HttpClient
    ↓
ASP.NET Core Pipeline
    ↓
Controller
    ↓
Application Service
    ↓
Entity Framework Core
    ↓
Real SQL Server

These testing styles are complementary rather than competing approaches.

Simple business rules are usually best covered by fast unit tests, while database behavior, HTTP pipelines and infrastructure boundaries can be validated with a smaller set of focused integration tests.

2. Why EF Core InMemory Is Not Always Enough

A common approach when developers first start testing EF Core applications is to use the EF Core InMemory provider.

It is easy to configure and fast to execute, but there is an important limitation:

EF Core InMemory is not SQL Server.

Some problems that exist in production SQL Server may never appear in a test environment using a fake provider.

Real relational behavior can matter for:

  • Foreign key constraints
  • Unique indexes
  • Transactions
  • SQL Server-specific queries
  • Collations and string comparisons
  • ROWVERSION
  • Computed columns
  • Raw SQL
  • Provider-specific LINQ translations

Testing against SQL Server provides far greater confidence that the application will behave the same way against the database engine used in production.

3. A Real Failure: Tests Pass but Production Fails

Suppose the Orders table must only contain one row for a given IdempotencyKey:

CREATE UNIQUE INDEX UX_Orders_IdempotencyKey
ON Orders(IdempotencyKey);

Assume the application accidentally fails to check for duplicate requests correctly.

A test setup that doesn't accurately reproduce relational database behavior may fail to reveal the issue.

A real SQL Server integration test will exercise the actual unique constraint when the second insert occurs.

Cannot insert duplicate key row...

The duplicate key value is (...)

This is one of the main reasons real-database integration tests are so valuable.

We are no longer testing only our C# code. We are testing the real contract between the application and SQL Server.

4. Technologies Used in the Example

ASP.NET Core
.NET 10
xUnit
WebApplicationFactory
Entity Framework Core
SQL Server
Testcontainers for .NET
Docker

The two most important infrastructure tools in this setup are WebApplicationFactory and Testcontainers.

WebApplicationFactory starts the ASP.NET Core application using a dedicated test host.

Testcontainers starts a disposable real SQL Server instance for the tests.

5. Creating the Test Project

dotnet new xunit -n ResilientShop.IntegrationTests

dotnet add ResilientShop.IntegrationTests reference ResilientShop.Api

dotnet add ResilientShop.IntegrationTests package Microsoft.AspNetCore.Mvc.Testing
dotnet add ResilientShop.IntegrationTests package Testcontainers.MsSql
dotnet add ResilientShop.IntegrationTests package Microsoft.EntityFrameworkCore.SqlServer

The environment running the tests needs access to an appropriate container runtime. In local development this is commonly Docker Desktop or Docker Engine.

6. Exposing Program to WebApplicationFactory

For ASP.NET Core applications using the minimal hosting model, the following definition can be added after app.Run():

app.Run();

public partial class Program
{
}

The test project can then use:

WebApplicationFactory<Program>

to bootstrap the System Under Test.

7. Starting a Real SQL Server Container

Testcontainers can create a real SQL Server instance for the test run:

using Testcontainers.MsSql;

public sealed class SqlServerFixture
    : IAsyncLifetime
{
    public MsSqlContainer Container { get; }

    public SqlServerFixture()
    {
        Container =
            new MsSqlBuilder(
                "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04")
                .Build();
    }

    public async Task InitializeAsync()
    {
        await Container.StartAsync();
    }

    public async Task DisposeAsync()
    {
        await Container.DisposeAsync();
    }
}

Once the container starts:

  • A real SQL Server instance is available.
  • The test receives an isolated database environment.
  • A dynamic connection string can be retrieved.
  • The entire environment can be removed after the tests finish.

Pinning the container image version is a good way to reduce unexpected test changes caused by a moving latest image.

8. Replacing the Production Connection String

Suppose the production application registers the DbContext like this:

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

The integration test must not connect to the production database.

We can replace the DbContext registration inside a custom WebApplicationFactory:

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

public sealed class CustomWebApplicationFactory
    : WebApplicationFactory<Program>
{
    private readonly string _connectionString;

    public CustomWebApplicationFactory(
        string connectionString)
    {
        _connectionString = connectionString;
    }

    protected override void ConfigureWebHost(
        IWebHostBuilder builder)
    {
        builder.UseEnvironment("Testing");

        builder.ConfigureServices(services =>
        {
            services.RemoveAll<
                DbContextOptions<ShopDbContext>>();

            services.RemoveAll<ShopDbContext>();

            services.AddDbContext<ShopDbContext>(
                options =>
                    options.UseSqlServer(
                        _connectionString));
        });
    }
}

The controller, middleware, application services and EF Core logic remain unchanged.

Only the infrastructure endpoint for SQL Server is replaced.

9. Running EF Core Migrations Before Tests

A new SQL Server container starts with an empty database.

We can apply our real migrations before executing the test:

using var scope =
    factory.Services.CreateScope();

var db =
    scope.ServiceProvider
        .GetRequiredService<ShopDbContext>();

await db.Database.MigrateAsync();

This gives us an additional benefit: the migration chain itself becomes part of the test.

If a development database contains a column that was manually created but never added to a migration, a clean SQL Server container can expose that mistake immediately.

10. Our First Real Integration Test

Assume the API contains:

POST /api/orders

with this request:

{
    "productId": 15,
    "quantity": 2
}

Checking only that the endpoint returns HTTP 201 isn't enough.

We should also verify that the correct data was persisted.

[Fact]
public async Task CreateOrder_ShouldPersistOrder()
{
    var container =
        new MsSqlBuilder(
            "mcr.microsoft.com/mssql/server:2022-CU14-ubuntu-22.04")
            .Build();

    await container.StartAsync();

    await using var factory =
        new CustomWebApplicationFactory(
            container.GetConnectionString());

    using (var scope =
        factory.Services.CreateScope())
    {
        var db =
            scope.ServiceProvider
                .GetRequiredService<ShopDbContext>();

        await db.Database.MigrateAsync();

        db.Products.Add(
            new Product
            {
                Id = 15,
                Name = "Test Product",
                Price = 750,
                StockQuantity = 10
            });

        await db.SaveChangesAsync();
    }

    var client = factory.CreateClient();

    var response =
        await client.PostAsJsonAsync(
            "/api/orders",
            new
            {
                ProductId = 15,
                Quantity = 2
            });

    Assert.Equal(
        HttpStatusCode.Created,
        response.StatusCode);

    using (var scope =
        factory.Services.CreateScope())
    {
        var db =
            scope.ServiceProvider
                .GetRequiredService<ShopDbContext>();

        var order =
            await db.Orders
                .SingleAsync();

        Assert.Equal(15, order.ProductId);
        Assert.Equal(2, order.Quantity);
        Assert.Equal(1500, order.TotalAmount);
    }

    await container.DisposeAsync();
}

This test exercises much more than a controller method.

HttpClient
    ↓
Routing
    ↓
Controller
    ↓
Service
    ↓
EF Core
    ↓
SQL Server
    ↓
Database Constraints

11. Testing Only the HTTP Response Is Not Enough

This test is incomplete:

var response =
    await client.PostAsJsonAsync(
        "/api/orders",
        request);

Assert.True(response.IsSuccessStatusCode);

The API might return 201 while storing incorrect state.

For example:

  • TotalAmount may be wrong.
  • Inventory may not have been reduced.
  • Two Orders may have been inserted.
  • A transaction may have partially completed.

A strong integration test often verifies both the HTTP contract and the persistent database state.

12. Real Problem: Concurrent Orders

One of the greatest benefits of using a real database is the ability to test concurrency behavior.

Suppose there is only one item in stock:

ProductId = 15
StockQuantity = 1

Two customers attempt to buy it at the same time:

Request A ──┐
            ├── concurrently
Request B ──┘

A broken implementation may let both requests read stock value 1 and successfully create two orders.

A real integration test can expose the problem:

[Fact]
public async Task ConcurrentOrders_ShouldNotOversell()
{
    await SeedProductAsync(
        productId: 15,
        stock: 1);

    var request = new
    {
        ProductId = 15,
        Quantity = 1
    };

    var task1 =
        _client.PostAsJsonAsync(
            "/api/orders",
            request);

    var task2 =
        _client.PostAsJsonAsync(
            "/api/orders",
            request);

    var responses =
        await Task.WhenAll(
            task1,
            task2);

    var createdCount =
        responses.Count(
            x =>
                x.StatusCode ==
                HttpStatusCode.Created);

    var conflictCount =
        responses.Count(
            x =>
                x.StatusCode ==
                HttpStatusCode.Conflict);

    Assert.Equal(1, createdCount);
    Assert.Equal(1, conflictCount);

    using var scope =
        _factory.Services.CreateScope();

    var db =
        scope.ServiceProvider
            .GetRequiredService<ShopDbContext>();

    var product =
        await db.Products.SingleAsync(
            x => x.Id == 15);

    Assert.Equal(0, product.StockQuantity);

    Assert.Equal(
        1,
        await db.Orders.CountAsync());
}

This validates an important question that is difficult to answer meaningfully with a mocked repository:

“When two operations arrive concurrently, do the application and SQL Server still preserve the business rule?”

13. Testing Unique Constraints and Idempotency

Assume our order endpoint supports an Idempotency-Key:

POST /api/orders
Idempotency-Key: order-2026-001

We can send the same logical request twice and verify that only one order exists.

[Fact]
public async Task SameIdempotencyKey_ShouldCreateOneOrder()
{
    var firstRequest =
        new HttpRequestMessage(
            HttpMethod.Post,
            "/api/orders");

    firstRequest.Headers.Add(
        "Idempotency-Key",
        "order-2026-001");

    firstRequest.Content =
        JsonContent.Create(
            new
            {
                ProductId = 15,
                Quantity = 1
            });

    var first =
        await _client.SendAsync(
            firstRequest);

    var secondRequest =
        new HttpRequestMessage(
            HttpMethod.Post,
            "/api/orders");

    secondRequest.Headers.Add(
        "Idempotency-Key",
        "order-2026-001");

    secondRequest.Content =
        JsonContent.Create(
            new
            {
                ProductId = 15,
                Quantity = 1
            });

    var second =
        await _client.SendAsync(
            secondRequest);

    Assert.True(first.IsSuccessStatusCode);
    Assert.True(second.IsSuccessStatusCode);

    using var scope =
        _factory.Services.CreateScope();

    var db =
        scope.ServiceProvider
            .GetRequiredService<ShopDbContext>();

    Assert.Equal(
        1,
        await db.Orders.CountAsync());
}

This test exercises both the application logic and the real database uniqueness protection.

14. Testing Transaction Rollback

Suppose order creation performs two operations:

  1. Reduce stock.
  2. Insert the order.

If inserting the order fails, the stock update must also be rolled back.

The expected state is:

Initial Stock : 10

Order operation begins
Stock becomes 8
INSERT Orders fails

ROLLBACK

Expected Stock : 10
Expected Orders : 0

This type of test validates real SQL transaction behavior rather than merely asserting that a service throws an exception.

15. Why Migration Tests Matter

Successfully creating an EF Core migration does not guarantee that the migration will run successfully on SQL Server.

Problems may include:

  • Invalid custom SQL.
  • Incorrect constraint ordering.
  • References to missing columns.
  • SQL Server-specific syntax mistakes.

If every clean test database is initialized using:

Empty SQL Server
      ↓
MigrateAsync()
      ↓
Latest Schema

the migration chain is continuously verified as part of the integration-test suite.

16. Tests Must Not Depend on Each Other

One of the most frustrating integration-test failures is a test that passes individually but fails when the whole suite runs.

For example:

Test A:
Inserted Product Id = 15

Test B:
Attempts to insert Product Id = 15

PRIMARY KEY violation

Common isolation strategies include:

  1. Create a new container for every test.
  2. Reuse one SQL Server container but create a separate database per test.
  3. Reuse one database and reset it to a known state before each test.

The first approach provides strong isolation but is slower.

The third is fast but depends on a reliable cleanup process.

17. Resetting the Database

For smaller projects, tables can be cleaned in foreign-key order:

await db.Database.ExecuteSqlRawAsync(
    """
    DELETE FROM OrderItems;
    DELETE FROM Orders;
    DELETE FROM Products;
    """);

Larger systems may use dedicated database-reset tooling or create a separate database for each test.

A test should never depend on data created by another test.

18. Parallel Test Execution

Integration tests sharing the same database can interfere with one another when executed in parallel.

One test may delete data while another is still using it.

When a shared database is used, parallel execution can be disabled for the collection:

[CollectionDefinition(
    "SqlServer",
    DisableParallelization = true)]
public sealed class SqlServerCollection
{
}

A more scalable alternative is to provide separate databases for parallel test workers.

19. Do We Need a New Container for Every Test?

No.

Starting SQL Server is naturally more expensive than executing a normal unit test.

Starting 500 separate SQL Server containers for 500 tests may make the test suite unnecessarily slow.

A balanced design can use:

Test Assembly
      ↓
One SQL Server Container
      ↓
Reset database per test
or
Create a separate database per test

Container lifetime and test-data isolation are related, but they are not the same architectural decision.

20. Should Integration Tests Call Real External APIs?

Suppose the Order API communicates with a real payment provider.

Calling the real payment system during every database integration test is usually undesirable.

If the purpose of the test is to validate our API and SQL Server integration, the payment client can be replaced with a controlled implementation:

builder.ConfigureServices(services =>
{
    services.RemoveAll<IPaymentClient>();

    services.AddSingleton<IPaymentClient>(
        new FakePaymentClient(
            result: PaymentResult.Success));
});

The database remains real, while infrastructure outside the intended test boundary remains deterministic.

21. Testing External-Service Failure

The fake can also simulate failure:

services.AddSingleton<IPaymentClient>(
    new FakePaymentClient(
        result: PaymentResult.Failed));

Then we can verify:

Payment Failed
      ↓
Safe HTTP/business response
      ↓
Order must not accidentally become Paid
      ↓
Database remains consistent

22. Authentication and Authorization Integration Tests

Assume an endpoint is restricted to Admin users:

[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteOrder(long id)
{
    ...
}

The following behavior should be validated:

No token
    → 401

Normal user
    → 403

Admin
    → 204

If the goal isn't to test the external identity provider itself, a controlled authentication handler can be used in the test environment.

However, if JWT validation or Identity integration is what the test is supposed to validate, mocking that layer would defeat the purpose.

23. Even 404 Scenarios Benefit from Real Integration Tests

Consider:

GET /api/products/999999

The expected result is:

HTTP 404

This single test validates routing, controller behavior, service wiring, the EF Core query against SQL Server and conversion of “not found” into the public HTTP contract.

24. Testing ProblemDetails

If the application uses centralized error handling, the error response contract should also be tested:

var response =
    await _client.PostAsJsonAsync(
        "/api/orders",
        invalidRequest);

Assert.Equal(
    HttpStatusCode.Conflict,
    response.StatusCode);

var problem =
    await response.Content
        .ReadFromJsonAsync<ProblemDetails>();

Assert.Equal(
    409,
    problem!.Status);

Assert.NotNull(
    problem.Extensions["traceId"]);

The test now verifies the public API contract instead of merely checking that an exception occurred.

25. Never Use Production as the Integration-Test Database

This sounds obvious, but an incorrect connection-string override can connect tests to the wrong database.

An additional guard can fail the test startup if the connection does not look like the expected isolated environment:

var connectionString =
    container.GetConnectionString();

if (!connectionString.Contains(
        "localhost",
        StringComparison.OrdinalIgnoreCase))
{
    throw new InvalidOperationException(
        "Unexpected integration test database.");
}
An integration test should never have permission to clean or mutate production data.

26. Time-Dependent Integration Tests

Direct dependence on system time can make boundary tests unstable.

if (order.ExpiresAt < DateTime.UtcNow)
{
    ...
}

Modern .NET applications can abstract time so the integration-test environment uses a controlled clock.

The database remains real, while time becomes deterministic.

27. Do Not Fix Tests with Random Delays

This is usually a warning sign:

await Task.Delay(5000);

Waiting five seconds because “the background worker has probably finished by now” makes tests:

  • Slow.
  • Flaky.
  • Unreliable under CI load.

A better approach is to poll for a specific condition with a bounded timeout:

var timeout =
    DateTime.UtcNow.AddSeconds(10);

while (DateTime.UtcNow < timeout)
{
    if (await OrderProcessedAsync(orderId))
        break;

    await Task.Delay(100);
}

When possible, a deterministic signal or synchronization mechanism is even better.

28. Integration Tests in CI/CD

One advantage of Testcontainers is that developers and CI runners can create comparable infrastructure.

Developer Machine
       ↓
Container Runtime
       ↓
SQL Server Container
       ↓
dotnet test


CI Runner
       ↓
Container Runtime
       ↓
SQL Server Container
       ↓
dotnet test

The CI environment must support the container runtime required by the tests.

A common pipeline order is:

Restore
   ↓
Build
   ↓
Unit Tests
   ↓
Integration Tests
   ↓
Publish

29. How Many Integration Tests Should We Write?

Writing integration tests for every simple business permutation can make the suite unnecessarily expensive.

A reasonable separation is:

Quantity > 0
Discount calculations
Simple business formulas

→ Unit Tests


Database transactions
Unique constraints
Concurrency
Migrations
HTTP pipeline
Authorization
SQL Server-specific behavior

→ Integration Tests

The goal is not to use the most expensive testing technique everywhere. The goal is to test each risk at the most appropriate level.

30. Valuable Integration-Test Scenarios

Scenario Expected Result
Valid order 201 + persisted Order
Product doesn't exist 404
Insufficient inventory 409 + no incorrect DB changes
Duplicate IdempotencyKey One business operation
Two concurrent buyers, one item At most one succeeds
Failure inside transaction Complete rollback
Migrations applied to empty DB Successful schema creation
Unauthorized request 401 / 403

31. Common Mistakes

Testing everything with EF Core InMemory

Important relational behavior may never be exercised.

Sharing a development database

Tests interfere with each other and developers receive inconsistent results.

Depending on test execution order

Test B should never require data created by Test A.

Asserting only HTTP status codes

Persistent state may still be incorrect.

Calling every real external dependency

The suite becomes dependent on network conditions, quotas and third-party availability.

Using latest container images

The underlying database version can change unexpectedly between test runs.

Ignoring database cleanup

Tests pass individually and fail when executed together.

32. A Reliable Integration-Test Architecture

               xUnit Test
                   │
                   ▼
          WebApplicationFactory
                   │
                   ▼
          ASP.NET Core TestServer
                   │
        ┌──────────┴──────────┐
        │                     │
        ▼                     ▼
Real Application        Controlled Fakes
Code                    for External APIs
        │
        ▼
 Entity Framework Core
        │
        ▼
Real SQL Server Container
        │
        ▼
Real Constraints
Transactions
Indexes
Migrations
Concurrency

33. Conclusion

ASP.NET Core integration testing is much more than sending an HTTP request to a controller and checking whether the response is 200.

Its real value is validating the components that will actually work together in production.

For SQL Server-based applications, real database integration tests can detect:

  • Migration problems
  • Unique constraint violations
  • Foreign key issues
  • Transaction failures
  • Concurrency bugs
  • SQL Server-specific query problems

before they reach production.

Using Testcontainers to create disposable SQL Server instances also removes the dependency on a developer's permanent local database.

The main question in an integration test should not simply be:

“Does my method return the expected value?”

The more valuable question is:

“When a real HTTP request, the real application pipeline and a real SQL Server instance work together, does the system still produce a correct and consistent result?”

Once automated tests can answer that question, integration testing becomes more than a code-quality technique. It becomes one of the most valuable safety layers between development and production.

```
//

0 Comments

Write Comment

E-Mail address will not be published