
Why Tests Pass on the EF Core InMemory Provider and Fail in Production
- كاتب موثّق
- EF Core 10
محتويات المقال
UseInMemoryDatabase, and the first version of the check failed the test "rejects ana@example.com when Ana@Example.com exists". So the developer rewrote the query with string.Equals(c.Email, email, StringComparison.OrdinalIgnoreCase). The test turned green and the change shipped. In production, on SQL Server, every sign-up now fails with InvalidOperationException: The LINQ expression ... could not be translated. The fake didn't just miss a bug. It caused one.
The common misconception
DbContext, same LINQ, no server to install, no data to clean up, and tests that run in milliseconds.
What actually happens
It's a list with a DbContext in front
Constraints the database enforces don't exist
Foreign keys: an order pointing at customer 999, who doesn't exist, saved on InMemory. SQLite and SQL Server both refused it. Unique indexes: a second customer with the same email saved on InMemory. Both databases threw. Column lengths: a 50-character name in a HasMaxLength(20)column saved on InMemory and SQLite. SQL Server threw "String or binary data would be truncated".Decimal precision: a price of 10.555 in a decimal(18,2)column read back as 10.555 on InMemory and SQLite, and as 10.56 on SQL Server.
DbUpdateException or a rounding difference your tests will never see.
Queries are judged by C#, not SQL
c.Email == "ana@example.com" found Ana@Example.com on SQL Server and found nothing on InMemory. Worse, InMemory accepts expressions a relational provider can't translate. string.Equals with StringComparison.OrdinalIgnoreCase ran fine on InMemory and threw "could not be translated" on both SQLite and SQL Server.
Whole features are missing
TransactionIgnoredWarning: transactions aren't supported, and if you suppress the warning they're silently ignored, so a rollback test proves nothing. FromSql threw, and so did ExecuteUpdate, which only relational providers support. Deleting an order without loading its lines left the lines behind as orphans, because InMemory doesn't support cascade deletes in the database. SQL Server and SQLite deleted them.
It isn't even the fast option
The fix: test the query where it will run
using Microsoft.EntityFrameworkCore;public sealed class SignUp(ShopDb db){ // Rewritten until the InMemory test passed public Task<bool> EmailTakenAsync(string email, CancellationToken ct) => db.Customers.AnyAsync(c => string.Equals( c.Email, email, StringComparison.OrdinalIgnoreCase), ct); // SQL Server: InvalidOperationException, could not be translated}using Microsoft.EntityFrameworkCore;public sealed class SignUp(ShopDb db){ // NormalizedEmail is set on save and has a unique index public Task<bool> EmailTakenAsync(string email, CancellationToken ct) { var normalized = email.Trim().ToUpperInvariant(); return db.Customers.AnyAsync(c => c.NormalizedEmail == normalized, ct); }}using Microsoft.EntityFrameworkCore;using Shop;using Xunit;public sealed class SignUpTests(SqlServerFixture fixture) : IClassFixture<SqlServerFixture>{ [Fact] public async Task Finds_an_email_in_any_case() { // Real SQL Server: a container in CI, LocalDB on a dev machine await using var db = fixture.CreateContext(); // Never committed, so it's rolled back when the context is disposed await db.Database.BeginTransactionAsync(); db.Customers.Add(new Customer { Email = "Ana@Example.com", NormalizedEmail = "ANA@EXAMPLE.COM" }); await db.SaveChangesAsync(); db.ChangeTracker.Clear(); var taken = await new SignUp(db) .EmailTakenAsync("ana@example.com", default); Assert.True(taken); }}EnsureDeleted and EnsureCreated. In a test on LocalDB, the check returned true, and the table was empty again once the context was disposed.
HasMaxLength and decimal(18,2) | |||
== on strings that differ in case | |||
ExecuteUpdate |
How to apply it in your project
Find the fakes Search your test projects for UseInMemoryDatabaseand list which tests check queries, constraints or transactions. Those are the ones giving false confidence.Stand up the real engine Run the production database in a container, with Testcontainers or your CI's services, or use SQL Server Developer Edition or LocalDB on developer machines. Isolate with transactions Create the database once per run, wrap each writing test in a transaction you never commit, and call ChangeTracker.Clear()before reading back what you wrote.Move logic tests above the queries Where you want speed, test business logic against a stubbed interface that returns results, and keep the LINQ in classes that are tested only against the database.
Key takeaways
The InMemory provider runs LINQ as C# over collections; it was built for EF Core's own tests and Microsoft discourages it as a fake. It doesn't enforce foreign keys, unique indexes, lengths or precision, and it compares strings with C# rules. It runs queries that SQL Server can't translate, so a test can pass for code that always fails in production. Transactions, raw SQL, ExecuteUpdateand database cascades don't work on it at all.Test queries against the engine you ship on, isolated with transactions, and stub above the data access for fast logic tests.
التعليقات (0)