Relational integration tests
Relational integration tests
Relational integration tests check behavior at the actual database boundary: constraints, query translation, rollback and concurrency. A mock collection cannot prove these guarantees.
Choose the production database engine for production-provider semantics, including collations, isolation, SQL functions and migrations. An isolated SQLite in-memory database gives fast relational tests, but SQLite is not SQL Server or PostgreSQL. Open its connection before building contexts and keep it open until the fixture ends; closing the last in-memory connection normally destroys the database. Use a fresh database for unrelated tests; never reuse tracked entities as evidence of persisted state. EnsureCreated is useful for fresh-schema fixtures, but does not validate the migration chain. Test migrations separately on a disposable database with the intended provider and representative synthetic schema history; inspect upgrade and rollback or recovery strategy. A Testcontainers workflow needs explicit approval, reviewed images by digest, isolated daemon/VM, readiness checks, finite startup and teardown, and no production connection fallback. Do not mount a host socket into untrusted workloads. The examples below use EF Core SQLite and fresh verification contexts. A concurrency token is application-managed here; increment it on writes. A caught DbUpdateException is not enough: inspect its provider error and confirm stored state.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Models, in-process integrations and actual runtime or UI tests are distinguished.
Verify a unique constraint with a fresh context
Insert a duplicate SKU. Assert SQLite unique-constraint error and inspect persisted count.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires reviewed Microsoft.EntityFrameworkCore.Sqlite 10.0.15 dependencies. Only a fixture-owned in-memory connection is used.
using System;using System.Linq;using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<StockDb>().UseSqlite(connection).Options;using (var setup = new StockDb(options)) { setup.Database.EnsureCreated(); setup.Rows.Add(new StockRow { Sku = "A", Units = 5, Version = 1 }); setup.SaveChanges();}using (var db = new StockDb(options)) { db.Rows.Add(new StockRow { Sku = "A", Units = 9, Version = 1 }); bool rejected = false; try { db.SaveChanges(); } catch (DbUpdateException e) when (e.InnerException is SqliteException { SqliteExtendedErrorCode: 2067 }) { rejected = true; } if (!rejected) throw new Exception("expected unique constraint");}using (var verify = new StockDb(options)) { if (verify.Rows.Count() != 1 || verify.Rows.Single().Units != 5) throw new Exception("persisted state mismatch"); Console.WriteLine("duplicate rejected; units=5; rows=1");}sealed class StockRow { public int Id { get; set; } public string Sku { get; set; } = ""; public int Units { get; set; } public int Version { get; set; } }sealed class StockDb(DbContextOptions<StockDb> options) : DbContext(options) { public DbSet<StockRow> Rows => Set<StockRow>(); protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<StockRow>().HasIndex(r => r.Sku).IsUnique(); builder.Entity<StockRow>().Property(r => r.Version).IsConcurrencyToken(); }}Expected result (not executed):
duplicate rejected; units=5; rows=1The provider-specific 2067 code is SQLite UNIQUE constraint failure. Dispose the failed context rather than treating its tracked pending entity as committed data.
Verify transaction rollback outside the tracked context
Change units and save inside an explicit transaction, then roll back and re-query.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires reviewed Microsoft.EntityFrameworkCore.Sqlite 10.0.15 dependencies. Only a fixture-owned in-memory connection is used.
using System;using System.Linq;using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<StockDb>().UseSqlite(connection).Options;using (var setup = new StockDb(options)) { setup.Database.EnsureCreated(); setup.Rows.Add(new StockRow { Sku = "A", Units = 5, Version = 1 }); setup.SaveChanges();}using (var db = new StockDb(options)) { using var tx = db.Database.BeginTransaction(); var row = db.Rows.Single(); row.Units = 2; row.Version++; db.SaveChanges(); tx.Rollback();}using (var verify = new StockDb(options)) { var row = verify.Rows.AsNoTracking().Single(); if (row.Units != 5 || row.Version != 1) throw new Exception("rollback failed"); Console.WriteLine("rollback: units=5; version=1");}sealed class StockRow { public int Id { get; set; } public string Sku { get; set; } = ""; public int Units { get; set; } public int Version { get; set; } }sealed class StockDb(DbContextOptions<StockDb> options) : DbContext(options) { public DbSet<StockRow> Rows => Set<StockRow>(); protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<StockRow>().HasIndex(r => r.Sku).IsUnique(); builder.Entity<StockRow>().Property(r => r.Version).IsConcurrencyToken(); }}Expected result (not executed):
rollback: units=5; version=1SaveChanges within the transaction does not imply that the outer transaction committed. The new context verifies stored values rather than the old tracked object.
Detect a stale write with two contexts
Load the same version twice. Commit the first update, then attempt the second against its stale original token.
Inspect the archived Fixture.csproj and use only an approved .NET 10 SDK. Build and run in an isolated lab with finite time and resource limits. Requires reviewed Microsoft.EntityFrameworkCore.Sqlite 10.0.15 dependencies. Only a fixture-owned in-memory connection is used.
using System;using System.Linq;using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<StockDb>().UseSqlite(connection).Options;using (var setup = new StockDb(options)) { setup.Database.EnsureCreated(); setup.Rows.Add(new StockRow { Sku = "A", Units = 5, Version = 1 }); setup.SaveChanges();}using var first = new StockDb(options);using var second = new StockDb(options);var a = first.Rows.Single(); var b = second.Rows.Single();a.Units = 4; a.Version++; first.SaveChanges();b.Units = 3; b.Version++;bool conflict = false;try { second.SaveChanges(); }catch (DbUpdateConcurrencyException) { conflict = true; }using var verify = new StockDb(options);var saved = verify.Rows.AsNoTracking().Single();if (!conflict || saved.Units != 4 || saved.Version != 2) throw new Exception("lost update");Console.WriteLine("stale write rejected; units=4; version=2");sealed class StockRow { public int Id { get; set; } public string Sku { get; set; } = ""; public int Units { get; set; } public int Version { get; set; } }sealed class StockDb(DbContextOptions<StockDb> options) : DbContext(options) { public DbSet<StockRow> Rows => Set<StockRow>(); protected override void OnModelCreating(ModelBuilder builder) { builder.Entity<StockRow>().HasIndex(r => r.Sku).IsUnique(); builder.Entity<StockRow>().Property(r => r.Version).IsConcurrencyToken(); }}Expected result (not executed):
stale write rejected; units=4; version=2This deterministic interleaving tests optimistic concurrency, not simultaneous database writer contention. Resolve or reject conflicts according to the domain rather than blindly overwriting.
Apply the concept
Design a migration test that adds a unique SKU index to a table already containing duplicates. State the expected failure, cleanup, and retry policy.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Relational integration tests — knowledge check
Apply the lesson concepts to the following scenarios.
Why keep a SQLite in-memory connection open?
What verifies a rollback?
Does EnsureCreated verify migrations?
What is required for application-managed optimistic concurrency?
What does SQLite testing not establish?