Introduction
In the previous lessons, we tested the order API from the HTTP layer through to the database. However, a reliable test infrastructure is not created simply by adding more tests. We must measure what the tests cover, monitor the results continuously, eliminate flaky tests, and run the suite automatically for every change.
In this final lesson, we will build and test the solution in a CI pipeline. We will evaluate unit and integration coverage separately, examine the difference between line and branch coverage, and see why using coverage percentage as the only quality indicator is misleading. The goal is not to force the project to reach an arbitrary number. The goal is to protect business-critical behavior with tests that are reliable, fast, and maintainable.
Key idea: Coverage shows which code was executed; it does not prove by itself that the code was tested correctly.
1. Understanding test coverage
Code coverage measures how much of the application code is executed while tests are running. The most common measurements are:
- Line coverage: The proportion of code lines executed by the tests.
- Method coverage: The proportion of methods called at least once.
- Branch coverage: The proportion of decision branches exercised in if, switch, and similar constructs.
- Statement coverage: The proportion of executable statements that were run.
A single test can produce deceptively high line coverage for the following method:
public decimal CalculateDiscount(Customer customer, decimal total) { if (customer.IsPremium) return total * 0.90m; return total; }
If we test only the premium-customer scenario, a large portion of the method may execute, but the non-premium branch remains untested. For code containing business rules, branch coverage and scenario coverage are therefore more meaningful.
When reviewing coverage results, ask the following questions:
- Are critical workflows such as payment, inventory, and order status changes tested?
- Are failure and error paths covered?
- Do integration tests verify real boundaries such as HTTP and the database?
- Is uncovered code genuinely low risk, or does it contain an important decision point?
2. Generating coverage reports with .NET
Assume that the test project includes the Coverlet collector. We can collect coverage from the solution root with the following command:
dotnet test \ --collect:"XPlat Code Coverage" \ --results-directory ./TestResults
The same command can also be run as one line in Windows PowerShell:
dotnet test --collect:"XPlat Code Coverage" --results-directory ./TestResults
The command produces a coverage file in addition to the test results. The path commonly looks like TestResults/<guid>/coverage.cobertura.xml. This file is not a human-friendly report by itself; it can be converted into an HTML report with a reporting tool. It is important to check which projects are included and whether test assemblies are excluded.
Including test projects themselves or technical files such as migrations can make the result misleading if those files are not part of the intended production surface. It is usually better to target the application layers that carry behavior and to document every exclusion. Excluding too many files, however, artificially inflates the percentage and hides risk.
3. Defining meaningful coverage goals
There is no single coverage percentage that is correct for every project. A project with 90 percent coverage that tests only successful paths may be less reliable than a project with 75 percent coverage that verifies critical failure scenarios.
An example policy could look like this:
| Area | Recommended focus |
|---|---|
| Domain and business rules | High branch coverage and thorough boundary-condition tests |
| Application services | Success paths, validation, exceptions, and dependency failures |
| API layer | HTTP status codes, validation, authorization, and ProblemDetails |
| Database access | Important queries, transaction behavior, and constraint failures |
| Configuration and startup code | Smoke or integration tests where behavior is significant |
To monitor coverage over time, use a two-level policy. The first level protects the minimum quality threshold of the current branch. The second requires new or changed code to be tested. This prevents new debt from growing without requiring the team to eliminate all historical debt immediately.
Failing the pipeline when coverage falls can be useful, but the team should have an explicit exception process for generated code, reporting changes, or intentionally excluded files. Adding meaningless tests only to pass a threshold weakens the test suite.
4. Separating unit and integration tests
Unit tests are usually fast and do not require external systems. Integration tests may run the ASP.NET Core host and combine components such as the HTTP pipeline, Entity Framework Core, and SQL Server. These groups have different purposes and should not be expected to run at the same speed.
We can mark xUnit tests with a clear category:
public class OrderApiTests { [Fact] [Trait("Category", "Integration")] public async Task Create_order_returns_created_response() { // Runs with WebApplicationFactory and a real test database. } }
Use consistent names such as Unit for unit tests, Integration for integration tests, and External for tests requiring an external service. The groups can then be run separately:
dotnet test --filter "Category=Unit" dotnet test --filter "Category=Integration" dotnet test --filter "Category!=External"
The filters work only if the team uses the same trait names consistently. Mislabeling an integration test as a unit test directly affects CI duration and reliability.
5. Identifying and fixing flaky tests
A flaky test sometimes passes and sometimes fails even though the application code has not changed. Flaky tests reduce confidence in the pipeline; teams eventually start rerunning failures instead of investigating them as real defects.
Common causes and solutions include:
- Time dependence: Replace DateTime.Now with a testable clock abstraction.
- Random data: Use a fixed seed or log the generated data when a test fails.
- Shared state: Let each test create its own data and clean it up afterward.
- Asynchronous waiting: Wait for an actual state transition instead of guessing with Task.Delay.
- Parallel execution: Isolate tests that use the same database record or static field.
- External services: Use mocks in unit tests and controlled fakes or containers in integration tests.
- Order dependence: Never rely on alphabetical order or execution order.
Rerunning a test until it becomes green is not a fix. If necessary, execute it repeatedly to reproduce the problem, then inspect logs and test data. A retry mechanism should be limited to clearly identified temporary infrastructure failures and should not conceal application defects.
6. Preparing a CI pipeline
The following GitHub Actions workflow is a basic pipeline for a solution that targets .NET 10. Adjust the project paths to match your solution:
name: dotnet-tests on: push: branches: [ main ] pull_request: permissions: contents: read jobs: test: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v7 - name: Setup .NET uses: actions/setup-dotnet@v6 with: dotnet-version: '10.0.x' - name: Restore run: dotnet restore - name: Build run: dotnet build --no-restore --configuration Release - name: Unit tests with coverage run: >- dotnet test tests/OrderApp.UnitTests/OrderApp.UnitTests.csproj --no-build --configuration Release --filter "Category=Unit" --collect:"XPlat Code Coverage" --results-directory ./TestResults/Unit - name: Integration tests run: >- dotnet test tests/OrderApp.IntegrationTests/OrderApp.IntegrationTests.csproj --no-build --configuration Release --filter "Category=Integration" --collect:"XPlat Code Coverage" --results-directory ./TestResults/Integration
For this pipeline to be reliable, SQL Server and any other required dependencies must also be available in the CI environment. If integration tests connect to a shared development database, their results become dependent on the environment. Prefer a container, an isolated test database, or temporary resources created by the pipeline.
Saving coverage reports as CI artifacts makes failures easier to investigate. Keep unit and integration results in separate directories so that reports and test outputs do not become mixed together.
7. Rules for maintainable test infrastructure
- Keep test projects separate from production projects and use consistent names.
- Make unit tests fast, deterministic, and independent of external systems.
- Make integration-test setup and cleanup explicit and visible.
- Standardize test-data creation with shared helpers, but avoid overly magical fixtures.
- Ensure each test verifies one behavior and has a useful failure message.
- Track coverage over time instead of relying on a single percentage.
- Separate restore, build, unit-test, and integration-test stages in CI.
- Manage flaky tests as visible technical debt in the backlog.
- When the pipeline becomes slow, remove unnecessary duplication without silently disabling critical tests.
8. Common mistakes
Assuming that percentage equals quality: Coverage measures execution. Tests with incorrect or weak assertions can still produce high coverage.
Making everything an integration test: Too many external dependencies slow the suite and make failures harder to diagnose. Most business rules should be verified quickly with unit tests.
Removing integration tests from CI: If they run only on a developer’s machine, real integration failures are discovered too late.
Using global state: Static caches, shared files, and fixed database records create hidden dependencies between tests.
Silencing tests: Instead of filtering out slow or failing tests, investigate the cause. If a test must be temporarily excluded, create an issue and define a return date.
9. Short practice exercise
- List the unit and integration test projects in your solution separately.
- Add [Trait("Category", "Integration")] to at least two integration tests.
- Generate reports for both groups with dotnet test --collect:"XPlat Code Coverage".
- Choose one critical service and one critical branch in the reports and determine whether they are covered.
- Create a deliberately time-dependent test, observe its flaky behavior, and fix it with a clock abstraction.
- Add the workflow above to the repository and verify that unit tests run on a pull request.
- Document your coverage policy: which scenarios are mandatory for each layer, and which exclusions are acceptable?
Conclusion
A professional test infrastructure is not defined by the number of tests, a coverage percentage, or one framework choice. A successful approach tests critical behavior at the appropriate level, deliberately separates unit and integration tests, produces deterministic results, and is verified by CI for every change.
Use coverage reports as a signal that supports decisions. Do not inflate the number artificially; use it to find missing scenarios. Do not postpone flaky tests, because an untrusted test eventually becomes a test that nobody runs. When projects, test data, and pipeline stages remain simple, the infrastructure stays maintainable as the application grows.
With this lesson, you have completed the journey from unit tests to API and database integration tests, and finally to a measurable, automated CI testing strategy.