ASP.NET Core Interview Question #207

How should database code be tested?

Testing, Deployment & Hosting Senior Advanced

Quick Interview Answer

The test strategy depends on what is being verified. Pure business logic should not require a database. Repository or EF Core behavior may require integration tests against a database engine with behavior close to production.

Detailed Explanation

The test strategy depends on what is being verified. Pure business logic should not require a database. Repository or EF Core behavior may require integration tests against a database engine with behavior close to production.

A simple fake can be useful when the database is not part of the behavior under test. However, an in-memory substitute may not reproduce relational constraints, SQL translation, transactions, collation, or provider-specific behavior.

For critical data-access tests, an isolated real test database or disposable containerized database can provide higher confidence.

Code Example

// Example test arrangement concept:
// 1. Create isolated test database.
// 2. Apply schema/migrations.
// 3. Seed known data.
// 4. Execute repository operation.
// 5. Assert persisted result.
// 6. Clean up the isolated database.