Testing standard¶
This page sets the rules for automated tests in ConnectSoft repositories and in services generated from ConnectSoft templates. It is written for engineers and AI agents that write or review tests. How each kind of test is built is explained in Testing and its sub-pages; validator tests have their own page, Validator tests.
Kinds of test¶
| Kind | Project suffix | Category | What it covers |
|---|---|---|---|
| Unit | .UnitTests |
Unit Tests |
One class or a small group in isolation; no network, database or file system. |
| Integration | .IntegrationTests |
Integration Tests |
Code against a real dependency: a database in a test container, a broker, or a live external API. |
| Acceptance | .AcceptanceTests |
Acceptance Tests |
A service end to end through its API, often as Reqnroll scenarios. |
| Architecture | .ArchitectureTests |
Architecture Tests |
Layer and dependency rules of the solution. |
| End-to-end UI | A dedicated end-to-end solution | Reqnroll tags | Browser flows with Playwright against a deployed environment. |
The suffixes match current practice in 320 of 352 test projects.
Rules¶
CS-TST-001: Use MSTest, Reqnroll and Playwright¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
One test framework keeps runners, test adapters, Reqnroll bindings, Playwright fixtures and pipeline filters the same everywhere. ADR-0106 makes MSTest the only unit and integration test framework.
Do¶
- Write unit, integration and architecture tests with MSTest (
[TestClass],[TestMethod]). - Write BDD scenarios with Reqnroll and
Reqnroll.MsTest. - Write browser tests with Playwright:
Microsoft.Playwright.MSTest.v4in ConnectSoft repositories, or plainMicrosoft.Playwrightdriven from Reqnroll hooks in a dedicated end-to-end solution.
Don't¶
- Add xUnit or NUnit to a ConnectSoft repository.
- Add SpecFlow. It is replaced by Reqnroll.
How to check¶
The changed test projects reference MSTest, Reqnroll.MsTest, Microsoft.Playwright.MSTest.v4 or Microsoft.Playwright, and no xUnit, NUnit or SpecFlow package.
CS-TST-002: Assert with MSTest assertions in new tests¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
FluentAssertions 8 is commercially licensed. MSTest assertions need no licence decision (ADR-0106).
Do¶
- Use
Assert,CollectionAssertandStringAssertin new tests. - Use
Assert.ThrowsExactly<T>orAssert.ThrowsExactlyAsync<T>for an expected exception type. - In a repository that already uses FluentAssertions 7.2.2, either style is acceptable.
Don't¶
- Add FluentAssertions to a repository that does not use it.
- Upgrade FluentAssertions to 8.x without a recorded licence.
How to check¶
New test files use MSTest assertions, or the repository already references FluentAssertions 7.2.2.
CS-TST-003: Name tests after the behaviour and the expected outcome¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A failing test's name is often all a reader sees in a pipeline report. ADR-0105 sets PascalCase names without underscores, which is the majority style and needs no CA1707 suppression.
Do¶
- Name each test method in PascalCase, stating the action, the condition and the expected outcome.
- Name the test class
<ClassUnderTest>UnitTests, or the matching suffix for other kinds of test.
Don't¶
- Use underscores, as in
Method_Scenario_Expected. - Use names that do not say what is expected, such as
Test1orCreateOrderWorks.
Example¶
How to check¶
New test methods are PascalCase, contain no underscore, and state an expected outcome.
CS-TST-004: Name test projects by kind and categorize tests to match¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
Pipelines select tests by project name and by category. Today the categories are spelled several ways: "Unit Tests" in 1,127 places and "Unit" in 305. A filter written for one spelling silently skips the other.
Do¶
- Name test projects with the suffix of their kind, as in the table above.
- Put
[TestCategory("<Kind> Tests")]on each test class, using the exact category names in the table.
Don't¶
- Invent a new category spelling for a kind that already has one.
- Mix kinds of test in one project.
How to check¶
New test projects use a suffix from the table. New test classes carry the category that matches their project.
CS-TST-005: Categorize tests that call live external systems as integration tests¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A test that calls a live external API, a shared database or a cloud resource fails when that system is slow, down or rate-limited. If it runs in the normal CI test step, it makes the build flaky and can change real data.
Do¶
- Put every test that reaches a system outside the test process in the "Integration Tests" category. Test containers started by the pipeline are the exception.
- Read the endpoint and credentials of such tests from configuration or user secrets.
- Keep such tests out of the default CI filter, or run them in a separate job.
Don't¶
- Call a live external system from a unit test.
- Put a credential for an external system in a test file.
How to check¶
Tests that use real HTTP endpoints, connection strings or cloud SDK clients carry the "Integration Tests" category.
CS-TST-006: Structure each test as Arrange, Act, Assert¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A test with one clear act and its assertions after it shows at a glance what it proves. A test that acts several times proves several things and fails for unclear reasons.
Do¶
- Set up, then perform one action, then assert on its outcome.
- Optionally mark the three parts with
// Arrange,// Actand// Assertcomments. - Write
// Act and assertwhen the act and the assertion are one call, as withAssert.ThrowsExactlyAsync.
Don't¶
- Interleave several acts and assertions in one test. Write several tests instead.
How to check¶
Each new test has one act, followed by assertions on that act.
CS-TST-007: Keep tests deterministic and independent¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A test that depends on the clock, on the order tests run in, or on state left by another test fails at random. Random failures teach the team to rerun builds instead of reading failures. ConnectSoft test projects run MSTest in parallel.
Do¶
- Use
TimeProviderwith a fake time provider instead ofDateTime.UtcNowin code under test, and start the fake clock at a fixed baseline (CS-TIM-004). - Create the data each test needs inside the test, with unique keys, and clean it up or isolate it.
- Wait for an observable condition with a timeout, not for a fixed delay.
Don't¶
- Depend on test execution order, or on static state shared between tests.
- Use
Thread.SleeporTask.Delayto wait for asynchronous work. - Move a fake clock across years in a test that hosts Orleans or other timer-driven services. Their timers fire for every skipped period.
How to check¶
New tests do not read the real clock, do not share mutable static state, and do not wait with fixed delays.
CS-TST-008: Meet the coverage target with one collector¶
Severity: major · Applies to: service, library, api-client, blazor, template, pipelines · Enforced by: manual (target: ENF-021) · Status: active
Why¶
ADR-0105 sets an 80% line coverage target with a ratchet. When two coverage collectors run in one test run, the pipeline produces two reports and the quality check may read the wrong one. The gate then fails or passes for reasons unrelated to the code.
Do¶
- Aim for 80% line coverage. A new repository starts with
codeCoverageThreshold: 80. - Raise a repository's threshold when its measured coverage allows. Never lower it (CS-DOD-003).
- Collect coverage with one collector, Coverlet (
XPlat Code Coverage). Disable the Microsoft code coverage data collector in the.runsettingsfile.
Don't¶
- Exclude production code from coverage to meet the threshold, other than generated code.
How to check¶
- The pipeline threshold is at least its previous value.
- The
.runsettingsenables one coverage collector. - The change adds no coverage exclusion, such as
[ExcludeFromCodeCoverage]or an exclude filter, for hand-written production code.
CS-TST-028: Choose personas, data and environment that tell correct code from broken code¶
Severity: major · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
A test proves a rule only when the broken code would produce a different result. An administrator bypasses the scope filter under test, seed data that every persona can see hides a missing filter, and a host time zone equal to the product default hides a missing conversion. Such tests stay green against the defect they were written for.
Do¶
- Run scope and permission tests as a persona without the bypass, whose scoped and unscoped answers differ.
- Seed at least one record that the persona must not see next to one it must see.
- Configure the time zone, culture or other environment value under test to differ from the test host's own.
- Sign out and check the signed-in identity before each persona switch.
Don't¶
- Test a filter, a fallback or a conversion only in a setup where its presence and its absence give the same answer.
How to check¶
For each persona, data set and environment value in a new test, name the result that broken code would produce. If it equals the expected result, the setup is wrong.
CS-TST-029: Start a test on evidence that its dependencies are ready¶
Severity: major · Applies to: service, blazor, template · Enforced by: manual · Status: active
Why¶
A host's Start() and a container's "started" state come before the host or container can serve. Background services create schemas afterwards, databases accept connections later, and events that provision records in other services are consumed later still. A test that proceeds on "started" passes on a fast machine and fails on a slow CI agent.
Do¶
- Before the first step, poll for the specific evidence the test needs, such as the table, a successful connection, or the derived record in the other service's API.
- Bound every poll with a timeout sized from measured timings, and fail with a message that names what never became ready.
Don't¶
- Treat a returned
Start(), a started container or a fixed delay as readiness. - Raise a timeout to make a failure disappear without measuring the operation it waits for.
How to check¶
Each fixture or hook that starts a host, a container or a cross-service flow waits for a named readiness condition before the test uses it.
CS-TST-031: Locate repository files from the source file, not from the binary folder¶
Severity: minor · Applies to: service, library, api-client, blazor, template · Enforced by: manual · Status: active
Why¶
Tests that read files from the repository, such as feature files, schemas or approved snapshots, often walk up from AppContext.BaseDirectory. When the build output is redirected, for example with --artifacts-path, the binary folder is outside the repository and every such test fails.
Do¶
- Anchor on the test's own source path with
[CallerFilePath], and resolve repository files relative to it. - Copy a file to the output folder when the test only needs to read it, and read it from there.
Don't¶
- Search upwards from the binary folder for a solution file or a
.gitfolder.
Example¶
/// <summary>
/// Resolves paths relative to the repository from the location of this source file.
/// </summary>
internal static class RepositoryPaths
{
/// <summary>
/// Gets the folder that contains this source file.
/// </summary>
/// <param name="sourceFile">The path of the calling source file, supplied by the compiler.</param>
/// <returns>The folder of the source file.</returns>
public static string SourceFolder([CallerFilePath] string sourceFile = "")
{
return Path.GetDirectoryName(sourceFile)!;
}
}
How to check¶
Run the suite once with an output path outside the repository. No test fails to find a file.
CS-TST-032: Never let a skipped test stand for a passing one¶
Severity: major · Applies to: service, library, blazor, template · Enforced by: manual · Status: active
Why¶
Assert.Inconclusive ends a test as skipped, and with MapInconclusiveToFailed set to false a skipped test does not fail the run. A test whose only job is to prove that something runs (a gate lets a test through, a scenario binds all its steps) then stays green when the thing under test wrongly skips.
Do¶
- In a test that proves code runs instead of skipping, catch
AssertInconclusiveExceptionand callAssert.Failwith its message. - Give every skip gate a test for each way through it: one that skips and one that runs.
- Set
MapInconclusiveToFailedtotrue, except in a project whose tests skip on purpose when an environment is missing; such a project says so in a comment next to the setting.
Don't¶
- Write a test with no assertion that passes only because the code under test did not skip.
- Report a run with skipped tests as passing without listing the skipped count.
Example¶
[TestMethod]
public void RequireRead_WhenReadFlagsSet_DoesNotSkip()
{
using var flags = TestEnvironment.Set(ReadFlagsOnly);
try
{
AcceptanceGates.RequireRead();
}
catch (AssertInconclusiveException ex)
{
Assert.Fail("RequireRead skipped: " + ex.Message);
}
}
How to check¶
- Every test of a skip gate, or of anything that may call
Assert.Inconclusive, fails rather than turns Inconclusive when it should run. - Each
.runsettingswithMapInconclusiveToFailedset tofalsehas a comment that says which tests skip on purpose.
CS-TST-033: Assert the request a client sends, not only where it sends it¶
Severity: major · Applies to: service, library, blazor, template · Enforced by: manual · Status: active
Why¶
A stub server (WireMock or a fake HttpMessageHandler) that matches on path and method answers any request to that path. When the test checks only the path, the method and the headers, a client that sends no body, or the wrong one, still passes.
Do¶
- For every call that sends a body, assert the body the stub received: compare it as JSON to the expected document.
- Assert the query string for calls that send parameters in it.
- Put the comparison in one shared helper that every client test uses.
Don't¶
- Leave the body unchecked because the stub's response is what the test asserts.
- Compare JSON as raw strings when property order or whitespace may differ.
Example¶
var entry = server.LogEntries.Single();
JsonAssert.AreEqual(expectedBody, entry.RequestMessage.Body);
How to check¶
Every test of a client call that sends a body or query parameters asserts what the stub received, not only the path, the method and the headers.