Covers the options for database testing with EF Core (in-memory provider, SQLite, SQL Server via Testcontainers), their fidelity gaps, and resetting state with Respawn, transaction rollback or per-test databases.
The EF Core in-memory provider is fast but not a relational database: it ignores constraints, transactions and SQL translation, so tests pass that would fail in production. Microsoft now advises against it for testing.
SQLite in-memory is relational and quick, but it is a different dialect: column types, schemas, collation and some LINQ translations differ from SQL Server.
For real confidence I run SQL Server in a container with Testcontainers, apply the real migrations once, and reset data between tests with Respawn (delete in foreign-key order) or a rolled-back transaction.
The trade-off: a few seconds of container start-up per run in exchange for testing the same engine you ship on.
"There are three options and they trade speed for fidelity. The EF Core in-memory provider is really a dictionary behind
DbSet. It doesn't translate LINQ to SQL, so a query that EF can't translate passes in tests and throws in production; it doesn't enforce foreign keys, unique indexes or required columns; and transactions are ignored. Even the EF Core docs now say not to use it for testing. SQLite in-memory is a real relational engine, so constraints and SQL translation are exercised, but it is a different dialect: no schemas, different decimal andDateTimeOffsethandling, case-sensitive comparisons by default, and anything SQL Server-specific likeFromSqlwith T-SQL, temporal tables or JSON columns won't behave the same.So for repository and query tests I use the real engine: Testcontainers starts SQL Server once per test run in a collection fixture, I run
Database.MigrateAsync()so the schema comes from the same migrations that go to production, and I reset data between tests. For resetting, Respawn is my default: it reads the foreign-key graph and issues deletes in the right order, skipping__EFMigrationsHistory, usually in tens of milliseconds. Transaction rollback is even faster, but it breaks as soon as the code under test commits its own transaction, usesExecuteUpdateon a different connection, or the test goes throughWebApplicationFactory, where each request gets a newDbContext.The mistake I see is teams using the in-memory provider for 'integration' tests and then being surprised by a translation exception or a unique-key violation in production. I'd still use fakes for unit testing business logic that sits above the repository, but any test whose point is the query runs against SQL Server."
| Option | Fidelity to SQL Server | Speed | Main gaps |
|---|---|---|---|
| EF Core in-memory provider | Low | Fastest | No SQL translation, constraints, transactions or raw SQL |
| SQLite in-memory | Medium | Fast | Dialect: schemas, types, collation, T-SQL features |
| LocalDB | High | Medium | Windows only; not in Linux CI agents |
| SQL Server via Testcontainers | Production-level | Container start ~5–15 s, then fast | Needs Docker in CI |
| Azure SQL test database | Production-level | Network latency | Shared state, cost |
| Strategy | Speed | Works when | Breaks when |
|---|---|---|---|
| Respawn | ~10–100 ms | Almost always | Tables you forgot to ignore (seed/reference data) |
| Transaction rollback | ~1 ms | Single connection, code doesn't commit | Code commits, multiple contexts, WAF requests |
| Database per test class | Seconds | Full isolation for parallel classes | Many classes: start-up cost adds up |
| Snapshot restore | Seconds | Large seeded datasets | Container restarts |
On [a claims system], [about 40] repository tests used the in-memory provider and all passed while a GroupBy query threw a translation exception in production. Moving them to SQL Server in Testcontainers with Respawn added [about 12 seconds] of container start to a [6-minute] pipeline and immediately surfaced [two more] untranslatable queries and a missing unique index.
Checks whether the candidate knows the fidelity gaps of fake databases and can set up fast, isolated tests against a real engine.
Green flags
Red flags
LINQ query
│ EF Core in-memory provider
▼
LINQ-to-Objects over in-memory lists (no SQL, no relational rules)
LINQ query
│ SqlServer provider
▼
Expression tree -> SQL -> SQL Server optimiser -> rows
Because the in-memory provider evaluates in .NET, it can run methods that SQL Server can't (string.Format, custom C# methods), and it uses C# semantics: string comparison is case-sensitive, nulls behave like C# nulls, not SQL three-valued logic. Microsoft's guidance for EF Core is to avoid it for testing and prefer the real database or the repository pattern with fakes.
| Area | SQL Server | SQLite |
|---|---|---|
Schemas (dbo.) |
Yes | No (EF ignores them) |
decimal |
Exact | Stored as TEXT/REAL; ordering and sum limitations in EF |
DateTimeOffset |
Native | Limited ordering/comparison in EF |
| Collation | Usually case-insensitive | Case-sensitive by default |
| Sequences, temporal tables, JSON columns | Yes | No / different |
It also needs the connection kept open for an in-memory database to survive between contexts.
Test run starts
└─ Collection fixture: MsSqlContainer.StartAsync() (once, ~5-15 s)
└─ db.Database.MigrateAsync() (once)
└─ Respawner.CreateAsync(conn, options) (reads FK graph once)
└─ Each test: Arrange data -> Act -> Assert -> ResetAsync()
Test run ends
└─ DisposeAsync() stops the container (Ryuk cleans up if the process dies)
Respawn queries INFORMATION_SCHEMA / sys.foreign_keys to build a dependency graph, then generates DELETE statements from leaf tables to root tables (it can also reseed identities). The generated script is cached on the Respawner, so each reset is one round trip. Tables in TablesToIgnore (migration history, reference data) are left alone.
Rollback relies on every command running on the same connection inside one open transaction. It fails when:
BeginTransaction and Commit itself (nested transactions aren't real in SQL Server);WebApplicationFactory, which creates a new scope and DbContext per request;ExecuteUpdate use another connection.xUnit runs test collections in parallel. Tests that share one database must be in the same collection ([Collection("db")]) so they run serially, or each collection gets its own database name on the same container.
Where; compare providers.Respawner.ResetAsync on a schema with 30 tables.WebApplicationFactory and see the data leak.An xUnit collection fixture that starts SQL Server once, applies migrations, and resets data with Respawn after each test.
#nullable enable
namespace Claims.Tests;
using Microsoft.Data.SqlClient;
using Microsoft.EntityFrameworkCore;
using Respawn;
using Respawn.Graph;
using Testcontainers.MsSql;
using Xunit;
// Code under test
public sealed class Claim
{
public int Id { get; set; }
public required string Reference { get; set; }
public decimal Amount { get; set; }
}
public sealed class ClaimsDb(DbContextOptions<ClaimsDb> options) : DbContext(options)
{
public DbSet<Claim> Claims => Set<Claim>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Claim>().HasIndex(c => c.Reference).IsUnique();
b.Entity<Claim>().Property(c => c.Amount).HasPrecision(18, 2);
}
}
// One SQL Server container for every test in the "db" collection
public sealed class SqlServerFixture : IAsyncLifetime
{
private readonly MsSqlContainer _sql = new MsSqlBuilder()
.WithImage("mcr.microsoft.com/mssql/server:2022-latest")
.Build();
private Respawner _respawner = null!;
public string ConnectionString => _sql.GetConnectionString();
public ClaimsDb CreateDb() => new(new DbContextOptionsBuilder<ClaimsDb>()
.UseSqlServer(ConnectionString).Options);
public async ValueTask InitializeAsync()
{
await _sql.StartAsync();
await using var db = CreateDb();
await db.Database.EnsureCreatedAsync(); // in a real project: MigrateAsync() with your migrations
await using var conn = new SqlConnection(ConnectionString);
await conn.OpenAsync();
_respawner = await Respawner.CreateAsync(conn, new RespawnerOptions
{
DbAdapter = DbAdapter.SqlServer,
TablesToIgnore = [new Table("__EFMigrationsHistory")]
});
}
public async Task ResetAsync()
{
await using var conn = new SqlConnection(ConnectionString);
await conn.OpenAsync();
await _respawner.ResetAsync(conn);
}
public async ValueTask DisposeAsync() => await _sql.DisposeAsync();
}
[CollectionDefinition("db")]
public sealed class DbCollection : ICollectionFixture<SqlServerFixture>;
[Collection("db")] // tests sharing the database run serially
public sealed class ClaimRepositoryTests(SqlServerFixture fx) : IAsyncLifetime
{
[Fact]
public async Task DuplicateReference_IsRejectedByUniqueIndex()
{
var ct = TestContext.Current.CancellationToken;
await using var db = fx.CreateDb();
db.Claims.Add(new Claim { Reference = "CL-1", Amount = 100m });
await db.SaveChangesAsync(ct);
db.Claims.Add(new Claim { Reference = "CL-1", Amount = 50m });
// The in-memory provider would let this pass; SQL Server enforces the index
await Assert.ThrowsAsync<DbUpdateException>(() => db.SaveChangesAsync(ct));
}
public ValueTask InitializeAsync() => ValueTask.CompletedTask;
public async ValueTask DisposeAsync() => await fx.ResetAsync();
}
DateTimeOffset, collation, schemas and T-SQL features differ. Instead: Use SQLite for speed only on simple schemas; run the query tests on SQL Server.EnsureCreated in tests while production uses migrations. Why it is wrong: Migrations go untested and can drift from the model. Instead: MigrateAsync() once per run.DbContext and connection, so data leaks between tests. Instead: Respawn or a database per test class.TablesToIgnore or reseed after reset.[Collection] so they run serially, or give each collection its own database on the shared container.TablesToIgnore.The rule I give teams: fake the database to test logic, use the real database to test data access. Once you accept that, the choice is mostly about how to make the real database cheap, and in .NET 10 Testcontainers plus Respawn is the standard answer. The remaining decision is isolation versus speed.
In practice I balance it by test purpose. The inner loop while coding should give feedback in seconds, so domain logic runs against fakes and is never blocked by Docker. Data-access and endpoint tests run against SQL Server on every PR, because that is where fidelity pays. If that layer grows past a few minutes, I don't drop fidelity; I split it: shared container per run, a database per collection so collections can run in parallel, and small per-test datasets so resets stay in the tens of milliseconds. Only when a team has no container runtime at all would I accept SQLite, and then I'd add a nightly run against real SQL Server.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Repository fake | Unit tests of business rules above data access | Fake must stay simple | Testing the query itself |
| SQLite in-memory | Simple schemas, fast inner loop | Dialect surprises | SQL Server features, decimals, JSON columns |
| SQL Server container + Respawn | Default for data-access and API tests | Docker in CI, ~10 s start | No container runtime available |
| Database per collection | Parallel collections, heavy suites | More start-up and memory | Small suites |
| Reset strategy | Typical cost | Scales with |
|---|---|---|
| Transaction rollback | ~1 ms | Nothing (but limited applicability) |
| Respawn | ~10–100 ms | Rows to delete and tables in the graph |
| Recreate database | Seconds | Schema size and migrations |
I measure the setup by suite duration and flaky-test rate, and I check the escaped-defect log: if data bugs still reach production, the tests aren't using the real engine or real migrations.
Not for anything that tests data access. The EF Core in-memory provider runs LINQ against in-memory collections; it never generates SQL, so untranslatable queries, SQL Server collation and case-sensitivity, null semantics, constraints, foreign keys, unique indexes and transactions all behave differently, and tests pass that would fail on SQL Server. Microsoft's EF Core testing docs discourage it for testing. It can still serve quick tests of application logic that merely uses a DbContext, where speed matters more than fidelity. For integration tests use SQL Server in Testcontainers (or SQLite in-memory as a compromise with a different dialect), and reset state with Respawn or rolled-back transactions.
Testcontainers for .NET starts real Docker containers from test code and gives you their connection details. With Testcontainers.MsSql you build new MsSqlBuilder().WithImage("mcr.microsoft.com/mssql/server:2022-latest").Build(), await StartAsync() in an IAsyncLifetime fixture, and pass GetConnectionString() to EF Core. Testcontainers.Redis works the same way.
To keep it fast:
WithReuse(true) locally to skip start-up between runs.In CI you need a Docker host: Linux GitHub Actions runners and Microsoft-hosted Ubuntu agents have one. The trade-off is seconds of start-up and a Docker dependency for tests that behave like production, unlike the in-memory provider.
Derive a factory from WebApplicationFactory<Program> and implement IAsyncLifetime. InitializeAsync starts an MsSqlContainer, and DisposeAsync disposes the container and then the factory. In ConfigureWebHost, point the app at the container with UseSetting("ConnectionStrings:Orders", ...). You can also swap the DbContext registration in ConfigureTestServices.
Run EF Core migrations once per fixture, so the tests use the real schema. Then reset rows before each test with Respawn, which deletes data in foreign-key order and keeps the schema.
Use it as an IClassFixture and every class gets its own database. For speed, share one container and give each class a unique database name. The trade-off is that real SQL Server catches what in-memory providers hide (constraints, transactions, SQL translation), at the price of Docker and a few seconds of start-up.
How to tell it (STAR)
**S:** At [company] a new reporting endpoint failed on every call in production even though every test was green. **T:** I needed to fix it fast and work out why our tests missed it. **A:** I traced it to a GroupBy that SQL Server couldn't translate; our tests used the EF Core in-memory provider, which just ran it in .NET. After the hotfix, I moved our [40] repository tests to SQL Server in Testcontainers with migrations applied once and Respawn between tests, and wrote an ADR so new tests followed suit. **R:** The pipeline grew by [about 12 seconds], the move immediately caught [two] more untranslatable queries and a missing unique index, and we had [no] data-access regressions in the following [two quarters].
Last updated 23 Nov 2026.