LESSON 16 OF 18

16. Integration Tests with a Real SQL Server Test Database

Learn how to test EF Core migrations, repositories, transactions, and CRUD operations against an isolated SQL Server database with reliable test data setup and cleanup.

75 dk 70

Introduction

In the previous lesson, we configured Entity Framework Core and SQL Server integration and prepared the data access layer for testing. In this lesson, we move one step further by writing integration tests against a real SQL Server database. These tests validate the relational behavior that the application actually depends on.

SQLite or the EF Core InMemory provider can be useful for fast feedback, but neither reproduces every SQL Server behavior. SQL Server-specific data types, foreign key constraints, transaction semantics, concurrency behavior, indexes, and query translation should be verified with the actual SQL Server provider when those behaviors are important to the application.

The goal is not to connect every method to a database. Instead, we will build a focused suite that validates the critical data access paths for the sample order application. The tests will apply migrations, exercise repository CRUD operations, verify transaction rollback, and clean up the database after execution.

What does a real database integration test verify?

An integration test executes several components together instead of isolating one class. The repository, DbContext, SQL Server provider, migrations, and database constraints participate in the same scenario. This allows us to answer questions such as:

  • Can all migrations be applied to an empty database?
  • Are repository queries translated and executed correctly by SQL Server?
  • Are related order and order-item records persisted and loaded correctly?
  • Are changes rolled back when a transaction fails?
  • Do unique and foreign key constraints produce the expected failure?
  • Can tests run without depending on data created by another test?

These tests are slower and more expensive than unit tests. Therefore, they should not repeat every business-rule permutation. Business logic belongs primarily in unit tests, while provider-specific and schema-dependent behavior belongs in a small set of integration tests.

Designing an isolated test database

The first rule is never to connect tests to a development or production database. Use a separate SQL Server instance, LocalDB, or a containerized SQL Server instance in CI. A unique database name for each fixture reduces collisions when tests run concurrently.

public static class TestDatabase {    public static string CreateConnectionString()    {        var databaseName = $"Orders_IntegrationTests_{Guid.NewGuid():N}";        var builder = new SqlConnectionStringBuilder        {            DataSource = "(localdb)\\MSSQLLocalDB",            InitialCatalog = databaseName,            IntegratedSecurity = true,            TrustServerCertificate = true,            ConnectTimeout = 30        };        return builder.ConnectionString;    } }

The SQL Server instance can be shared, but each fixture owns its own database. That database must be removed after the test run. Also verify that the connection string cannot point to production and enable destructive cleanup only in the test environment.

Applying migrations at startup

For a migration-based application, applying migrations to the test database is more representative than calling EnsureCreated. EnsureCreated creates a schema directly from the model and does not create the migrations history required by a migration-based deployment. Tests should follow the same schema evolution path as the application.

public sealed class SqlServerDatabaseFixture : IAsyncLifetime {    private readonly string _connectionString = TestDatabase.CreateConnectionString();    public string ConnectionString => _connectionString;    public async Task InitializeAsync()    {        var options = new DbContextOptionsBuilder<OrdersDbContext>()            .UseSqlServer(_connectionString)            .Options;        await using var db = new OrdersDbContext(options);        await db.Database.MigrateAsync();        await SeedReferenceDataAsync(db);    }    public async Task DisposeAsync()    {        await using var connection = new SqlConnection(_connectionString);        await connection.OpenAsync();        var databaseName = connection.Database;        var masterConnection = new SqlConnection(            connection.ConnectionString.Replace($"Database={databaseName}", "Database=master"));        await masterConnection.OpenAsync();        await using var command = masterConnection.CreateCommand();        command.CommandText = $"ALTER DATABASE [{databaseName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{databaseName}];";        await command.ExecuteNonQueryAsync();    }    private static async Task SeedReferenceDataAsync(OrdersDbContext db)    {        db.Products.Add(new Product { Id = 100, Name = "Keyboard", Price = 75m });        await db.SaveChangesAsync();    } }

In production-quality test infrastructure, the database name should be generated by the test code and not supplied by an untrusted user. Even in tests, do not concatenate user-controlled table, database, or column names into SQL. Cleanup may require SQL Server-specific handling such as SINGLE_USER WITH ROLLBACK IMMEDIATE when open connections remain.

Creating contexts and testing repositories

Create a new DbContext for each test so that change tracking does not leak between scenarios. If multiple tests share the fixture database, each test must create its own data and clean it up. A transaction with rollback is often efficient, but tests that verify commit behavior require an additional cleanup strategy.

public sealed class OrderRepositoryTests    : IClassFixture<SqlServerDatabaseFixture> {    private readonly SqlServerDatabaseFixture _fixture;    public OrderRepositoryTests(SqlServerDatabaseFixture fixture)    {        _fixture = fixture;    }    private OrdersDbContext CreateContext()    {        var options = new DbContextOptionsBuilder<OrdersDbContext>()            .UseSqlServer(_fixture.ConnectionString)            .EnableDetailedErrors()            .Options;        return new OrdersDbContext(options);    }    [Fact]    public async Task AddAsync_PersistsOrderAndItems()    {        await using var db = CreateContext();        var repository = new OrderRepository(db);        var order = new Order        {            CustomerId = 42,            Items = new List<OrderItem>            {                new() { ProductId = 100, Quantity = 2, UnitPrice = 75m }            }        };        await repository.AddAsync(order);        await db.SaveChangesAsync();        await using var verificationDb = CreateContext();        var saved = await verificationDb.Orders            .Include(x => x.Items)            .SingleAsync(x => x.Id == order.Id);        saved.CustomerId.Should().Be(42);        saved.Items.Should().ContainSingle();        saved.Items[0].Quantity.Should().Be(2);    } }

Notice that verification uses a second context. This proves that the result was persisted to SQL Server rather than merely remaining in the first context's change tracker.

Writing balanced CRUD tests

The purpose of CRUD tests is not to repeat every line of repository code. The purpose is to protect the important data access contract. For most repositories, a useful starting set contains these scenarios:

  1. A new record is inserted together with its related records.
  2. A query loads the navigation properties required by the application.
  3. An update changes only the expected fields.
  4. A delete follows the configured foreign key and cascade behavior.

The not-found behavior should also be explicit. Your repository may return null, a result type, or a custom exception. The test should reflect the repository contract rather than impose a different one.

[Fact] public async Task GetByIdAsync_WhenOrderDoesNotExist_ReturnsNull() {    await using var db = CreateContext();    var repository = new OrderRepository(db);    var result = await repository.GetByIdAsync(Guid.NewGuid());    result.Should().BeNull(); }

Verifying transaction behavior

Creating an order may involve an order header, order items, and inventory movement. If one operation fails, the earlier operations must not remain committed. A transaction test should verify not only that an exception was thrown, but also that the database returned to its previous state.

[Fact] public async Task CreateOrder_WhenStockUpdateFails_RollsBackAllChanges() {    await using var db = CreateContext();    await using var transaction = await db.Database.BeginTransactionAsync();    var order = new Order    {        CustomerId = 77,        Items = new List<OrderItem>        {            new() { ProductId = 100, Quantity = 9999, UnitPrice = 75m }        }    };    db.Orders.Add(order);    Func<Task> act = async () =>    {        await db.SaveChangesAsync();        throw new InvalidOperationException("Simulated stock failure");    };    await act.Should().ThrowAsync<InvalidOperationException>();    await transaction.RollbackAsync();    await using var verificationDb = CreateContext();    var exists = await verificationDb.Orders        .AnyAsync(x => x.CustomerId == 77);    exists.Should().BeFalse(); }

If the application service owns the transaction, call the real service method rather than opening a replacement transaction in the test. The test should observe the transaction boundary implemented by the application and verify its result when a failure occurs.

Test data setup and cleanup strategies

Stable and readable test data makes tests easier to understand. However, shared databases can produce conflicts when tests reuse the same natural keys. Generate unique e-mail addresses, order numbers, or customer codes when necessary.

  • Database per test: Provides the strongest isolation, but creation and migration take longer.
  • Database per test class: A fixture starts one database; each test creates and removes its own data.
  • Transaction rollback: Fast and convenient, but requires care with commits, background tasks, and separate connections.
  • Table cleanup: Useful when testing committed changes; foreign key order and identity values must be handled correctly.

Separate reference data from scenario data. A product category or currency can be seeded when the fixture starts. The customer and order that determine the outcome should be created inside the test's Arrange phase.

Common mistakes

  • Using a production connection: Keep test settings separate and validate that the connection points only to an approved test server.
  • Using EnsureCreated instead of migrations: This bypasses migration history and can hide deployment problems.
  • Verifying with the same context: Change tracking can make an operation appear successful. Use a new context for persistence verification.
  • Relying on test order: Every test should create its own data and should not depend on a record created by another test.
  • Parallel test collisions: Shared databases and fixed unique values can conflict. Generate unique names or limit the relevant test collection.
  • Ignoring cleanup failures: A failed cleanup can leave later runs with dirty data. Log cleanup errors and make them visible.

Practice exercise

Complete the following exercise:

  1. Create a fixture that generates a unique SQL Server test database name.
  2. Apply all application migrations with MigrateAsync.
  3. Write a repository integration test that creates an order and its items.
  4. Use a new context to verify that the order was actually persisted.
  5. Create an invalid foreign key or insufficient-stock scenario and verify that the order does not remain after rollback.
  6. Delete the database or safely clean its tables after the test run.

As an extension, run the tests in parallel. If a failure appears, determine whether it is caused by fixed test data, a shared database, or an application-level concurrency issue.

Conclusion

Real SQL Server integration tests show that not only the C# code, but also migrations, SQL queries, relationships, constraints, and transaction behavior work together correctly. A reliable setup combines an isolated database, migration-based initialization, new-context verification, controlled test data, and dependable cleanup.

With this foundation, the data access layer can be tested with confidence. In the next lesson, we will move these checks to the API boundary and verify complete order scenarios from an HTTP request through to the final state in SQL Server.

Sources