Test data and databases¶
This page sets the rules for the databases that tests create, drop and fill, and for the data each test relies on. It is written for engineers who write unit, acceptance and end-to-end tests that touch a database, and for reviewers of test fixtures. Following it means a test run never damages a runtime database, and a test fails for the reason its name gives.
Patterns for builders, factories and seeders are explained in Test data management. Independence and determinism in general are covered by CS-TST-007.
Runtime databases are off limits to tests¶
A developer machine and a shared test server usually run real services next to the tests, on the same SQL Server instance. Those services hold live connections, and their databases reference each other. A test fixture that drops, migrates down or deletes from one of them can leave the whole environment broken, while the test run reports success.
- A test only drops or recreates a database that the test suite itself owns and creates.
- Before you run a suite you did not write, check which database names its settings and its fixtures use.
- Dropping or recreating a runtime database is an operator decision. Report what is needed and let the owner of that environment do it.
Rules¶
CS-TST-016: Give each test database a name unique to its suite¶
Severity: blocker · Applies to: service, library, template · Enforced by: manual (target: ENF-055, ENF-056) · Status: active
Why¶
Acceptance suites drop and recreate their database. When the name is generic, such as MicroserviceDatabase, or equal to the database a running site uses, one suite drops another suite's database or a hosted service's data. A template passes its name on to every service generated from it, so a shared name in a template spreads.
Do¶
- Name each test database after the repository and the kind of test, in the form
<Repository><Kind>Tests, for exampleOrderServiceAcceptanceTests,OrderServiceMappingTestsorOrderServiceMigrationTests. - Use the same name in the test constant that the drop uses and in the connection strings that the test host uses.
- In a template, derive the name from the template's name placeholder, so that a generated service gets its own name.
Don't¶
- Use a name that a runtime, development or hosted database uses.
- Use a generic name shared by several repositories, such as
MICROSERVICE_DATABASE. - Drop a database whose name differs from the one the test host connects to.
Example¶
internal static class TestConstants
{
/// <summary>The database that the acceptance suite owns, creates and drops.</summary>
internal const string DbName = "OrderServiceAcceptanceTests";
}
How to check¶
- The
DbNameconstant and everyDatabase=value in the test settings end withTestsand include the repository name. - No test database name appears in the application's runtime
appsettingsfiles.
CS-TST-017: Point fixtures at their own database in code¶
Severity: blocker · Applies to: service, library, template · Enforced by: manual (target: ENF-056) · Status: active
Why¶
Test settings files are often copies of the application's settings, with the runtime connection string in them. A migration fixture that calls MigrateDown(0), a calendar fixture that deletes rows, or a mapping test that commits a round-trip row then works on the runtime database. The suite stays green, and the damage appears later as a service defect.
Do¶
- In every fixture that migrates, seeds, deletes or commits rows, build the connection string from the configured one with
SqlConnectionStringBuilderand setInitialCatalogto the fixture's own database. - Feed the rewritten string back through configuration, so that the ORM, which resolves its connection by name, follows it.
- Create the fixture's database inside the fixture, for example with
CreateIfNotExistsfollowed byMigrateUp.
Don't¶
- Run
MigrateDown,DELETE,TRUNCATEorDROPagainst a connection string read unchanged from settings.
Example¶
string configured = configuration.GetConnectionString(ConnectionStringKey)!;
string mappingTests = new SqlConnectionStringBuilder(configured)
{
InitialCatalog = "OrderServiceMappingTests",
}.ToString();
IConfiguration fixtureConfiguration = new ConfigurationBuilder()
.AddConfiguration(configuration)
.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:" + ConnectionStringKey] = mappingTests,
})
.Build();
How to check¶
Every fixture that calls MigrateDown, DELETE FROM, TRUNCATE or DROP DATABASE also sets InitialCatalog.
CS-TST-018: Clear the connection pools after you drop a database¶
Severity: major · Applies to: service, template · Enforced by: manual (target: ENF-055, ENF-056) · Status: active
Why¶
The SQL Server connection pool belongs to the test process and is keyed by the connection string, so it outlives the host of one feature. After a suite drops and recreates its database, a pooled connection still points at the dropped one. The next request fails, typically with SQL error 18456 when the pooled connection is reset, and the failure looks like a password problem in CI.
Do¶
- Call
SqlConnection.ClearAllPools()right after a successful drop.
Don't¶
- Drop a database that the same process has used, without clearing the pools.
Example¶
new SqlServerDatabaseHelper().ExecuteSql(
connectionString,
$"USE master; ALTER DATABASE [{dbName}] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [{dbName}];");
SqlConnection.ClearAllPools();
How to check¶
Every DROP DATABASE in test code is followed by SqlConnection.ClearAllPools().
CS-TST-019: Make each test own the data it uses and give back what it consumes¶
Severity: major · Applies to: service, blazor, template · Enforced by: manual · Status: active
Why¶
Suites that run against a long-lived environment see data grow with every run. A fixture that finds its subject by a name that is not unique picks a namesake left by an earlier run. A scenario that takes an item from a finite seeded pool, such as an employee without a login, empties the pool after a few runs. Both pass on a fresh database and fail later in a way that looks like a product defect.
Do¶
- Create the data a test needs with keys generated for that test.
- Locate an existing record by the unique key that the later steps use, and filter search results by it.
- Seed only the shortfall: create nothing when the environment already holds what the scenario needs.
- Return to a seeded pool what a scenario takes from it, in a cleanup hook.
- Prove that a fixture is repeatable by measuring the pool before and after a run.
Don't¶
- Take the first row of a search by name, then act with an identifier that belongs to a specific record.
- Create data on every run when the scenario only needs it to exist once.
How to check¶
New fixtures locate records by unique keys, and scenarios that consume seeded data have a cleanup hook.
CS-TST-020: Guard every collection assertion against an empty set¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual (target: ENF-058) · Status: active
Why¶
Enumerable.All over an empty sequence is true, and a foreach whose body holds the only assertion runs zero times. An assertion over a filtered subset is most at risk, because the filter is often empty in exactly the failure being tested. Assert.IsGreaterThanOrEqualTo(0, count) can never fail.
Do¶
- Assert that the collection, or the filtered subset, is not empty, or has the expected count, before asserting on its items.
- When an earlier step of the same scenario already proves the collection is not empty, keep that step next to the assertion it protects.
Don't¶
- Assert only
items.All(...)or loop over items without a count assertion. - Write assertions that cannot fail, such as a count being at least zero.
Example¶
// Do
IReadOnlyList<Order> closed = orders.Where(order => order.ClosedOn is not null).ToList();
Assert.HasCount(2, closed);
Assert.IsTrue(closed.All(order => order.ClosedOn <= now));
// Don't
Assert.IsTrue(orders.Where(order => order.ClosedOn is not null).All(order => order.ClosedOn <= now));
How to check¶
Search new tests for .All( inside an assertion and for foreach loops that contain the only assertions, and check that a count assertion precedes them.
CS-TST-021: Prove that nothing was written with a write counter¶
Severity: major · Applies to: service, library · Enforced by: manual · Status: active
Why¶
An assertion on end state, such as "no file is stored", cannot see a write that a compensating action later undid. The code under test can store a file, refuse the request, and delete the file again, and the test still passes. A guard that should stop the write can then be removed without any test failing.
Do¶
- When the requirement is that a write never happens, have the test double count calls, and assert that the count is zero.
- Check that a guard is needed by removing it and watching a test fail.
Don't¶
- Use the final contents of a fake store as proof that nothing was written.
How to check¶
Tests of "rejected before storing" assert a call counter of the fake, not only its final contents.
CS-TST-022: Count seeded rows by the seed's own identifiers¶
Severity: minor · Applies to: service, template · Enforced by: manual · Status: active
Why¶
A seed test that counts rows by a referenced value, such as the owner or creator, breaks when that value changes. The positive test then fails with a message that reads as "the seed did not run", and the negative test, which expects zero rows, keeps passing whatever happens.
Do¶
- Count seeded rows by the identifiers the seed itself inserts, the same ones its
Down()deletes. - Check that the same query returns the full count when the seed runs and zero when it must not.
Don't¶
- Count seeded rows by owner, creator or any other shared reference.
How to check¶
Seed tests filter on the seed's own key column.
CS-TST-023: Find a created row by walking the pages or by filtering to it¶
Severity: major · Applies to: service, blazor, template · Enforced by: manual · Status: active
Why¶
A shared test database grows with every run. An assertion that a new row appears on the first page of an unfiltered list passes while the table is small and fails once the new row sorts beyond it. The failure reads as "the save was lost", and waiting longer does not help.
Do¶
- Filter or search the list to the row the test created, by its unique key.
- When the test must check the list itself, walk the pages until the row is found, and fail with a message that says the row was created and is on none of the pages.
Don't¶
- Assert that a row appears on the first page of an unfiltered list.
- Rely on a large page size to keep a list on one page.
How to check¶
List assertions in acceptance and end-to-end tests filter by a unique key or walk the pages.
CS-TST-030: Fail a capture-and-restore hook when the captured value was not found¶
Severity: major · Applies to: service, blazor, template · Enforced by: manual · Status: active
Why¶
A hook that captures shared state before a scenario and writes it back afterwards destroys that state when the capture silently fails. Lookup helpers often return an empty value for a missing key, and many APIs accept an empty value as "clear all", so the restore deletes data that later suites need.
Do¶
- Assert that the captured value was found, and is not empty when emptiness is not a valid state, before the scenario changes anything.
- After the restore, assert that the restored state equals the captured state.
- Return "not found" from lookup helpers as a distinct result, not as an empty collection.
Don't¶
- Write back a captured value that the hook never checked.
How to check¶
Every hook that writes captured state back asserts on the capture first and on the restored state afterwards.