Zum Inhalt springen

Coverage gates in .NET with diff coverage and mutation testing

A 100% coverage gate lets weak tests through. Diff coverage stops untested code, and mutation tests find weak assertions.

by CodeCharter
  • testing
  • code-coverage
  • code-quality

A tech lead has set up a gate requiring 100% line coverage for the pull requests of a .NET solution. A PR adds the method ApplyDiscount, which calculates the reduced price from an amount and a discount rate, along with a test for it. The example is deliberately small and leaves out input validation:

public static decimal ApplyDiscount(decimal amount, decimal rate)
    => amount - amount * rate;

[Fact]
public void DiscountedPriceIsPositive()
{
    decimal result = PriceCalculator.ApplyDiscount(100m, 0.10m);
    Assert.True(result > 0m);
}

CodeCharter v1.7.0 runs the tests and reports full coverage:

> codecharter coverage --min-coverage 100
coverage: 1 test project(s) discovered
…
Line coverage 100% meets the required minimum of 100%.
Coverage: 1/1 lines = 100% (required 100%, source: cli-flag). 0 uncovered region(s) in 0 file(s). Test projects: 1 passed, 0 failed.

The test only checks that the result is positive. It would also pass if the method calculated amount + amount * rate, because 110 is greater than zero as well. The solution and its Git history are constructed for this article; the outputs come from real runs.

Meaning of line coverage

If the developer replaces the assertion with a concrete expectation, the gate's output does not change:

[Fact]
public void TenPercentDiscountReducesOneHundredToNinety()
{
    decimal result = PriceCalculator.ApplyDiscount(100m, 0.10m);
    Assert.Equal(90m, result);
}

This run also reports 1/1 lines = 100%. Line coverage counts which lines a test executed. Whether the test checks the result is not part of the number.

Conditions add a second gap. A later PR adds PriceFor, which gives members a ten percent discount. To do so, it calls ApplyDiscountRounded, the variant of ApplyDiscount rounded to the cent, which came with its own test in an earlier PR. Only the member price is tested:

public static decimal PriceFor(decimal amount, bool isMember)
    => isMember ? ApplyDiscountRounded(amount, 0.10m) : amount;

[Fact]
public void MemberPaysNinetyOfOneHundred()
{
    Assert.Equal(90m, PriceCalculator.PriceFor(100m, isMember: true));
}

The gate on the changed lines reports 1/1 changed lines = 100% and ends with exit code 0. The Cobertura file that coverlet wrote in the same run shows that the branch for non-members never ran:

<line number="32" hits="1" branch="True" condition-coverage="50% (1/2)">

For the gate, CodeCharter reads only the line values. It does not check branch coverage, so a ternary that ran only halfway passes a 100% gate.

Larger studies reach a similar result. Inozemtseva and Holmes (ICSE 2014) generated 31,000 test suites for five Java systems. They measured the suites' effectiveness against artificially seeded faults. With the number of tests held constant, effectiveness correlated only weakly to moderately with coverage. The suites rarely reached very high coverage, and the authors do not rule out an effect that only appears there. They advise using coverage to find undertested parts of a system, but not as a quality target.

Chekam, Papadakis, Le Traon and Harman (ICSE 2017) compared several test criteria on four C programs with 61 real faults. At equal suite size, suites with higher statement or branch coverage found practically no more faults. Neither study examines .NET unit tests; Chekam and colleagues worked with system tests run from the command line. The number therefore shows where no test reaches. Whether a test detects a wrong value is checked by a different tool.

A mutation test on the same code

A mutation test deliberately injects faults into the code and reruns the tests for each variant. Such a variant is called a mutant. If at least one test fails, the mutant counts as killed; if all tests pass, it has survived. The mutation score is the share of killed mutants. For .NET, Stryker.NET does this job; in the example, it runs as a local .NET tool from a tool manifest.

Stryker.NET v5.1.0 creates two mutants for ApplyDiscount with the weak test. The console reports the score:

> dotnet stryker --reporter cleartext --reporter json
[23:27:37 INF] 2 mutants created
…
[23:27:42 INF] The final mutation score is 50.00 %

Which mutants survived is listed in mutation-report.json:

#0 Survived   Arithmetic mutation   L11:12 -> amount + amount * rate
#1 Killed     Arithmetic mutation   L11:21 -> amount / rate

The surviving mutant is exactly the fault from the introduction. Even the weak assertion kills the second one, because 100 − 100 / 0.1 gives −900. With the test Assert.Equal(90m, result), both mutants die and the score rises to 100%. Without a configured threshold, Stryker ends with exit code 0 even when a mutant survives. Someone therefore has to read the report, or the surviving mutant has no consequence.

On the ternary in PriceFor, Stryker finds the branch that line coverage reports as covered. The report contains these mutants for it:

…
#3 Survived   Conditional (true) mutation    L32:12 -> (true?ApplyDiscountRounded(amount, 0.10m) :amount)
#4 Killed     Conditional (false) mutation   L32:12 -> (false?ApplyDiscountRounded(amount, 0.10m) :amount)

The mutant that always returns the member price survives because no test expects a price for non-members. A second test that expects the unchanged amount for isMember: false fails against this mutant.

A score of 100% means that all generated mutants were killed. For the line Math.Round(ApplyDiscount(amount, rate), 2, MidpointRounding.AwayFromZero) in ApplyDiscountRounded, Stryker v5.1.0 generated no mutant. Whether the result is rounded to two decimal places is checked there only by the method's own test, which expects 16.99 from 19.99 at a 15% discount. That test does not check the rounding mode: 16.9915 is not a midpoint, so AwayFromZero and the default ToEven both return 16.99.

Papadakis, Shin, Yoo and Bae (ICSE 2018) used 68 C faults and 231 Java faults to examine whether the mutation score relates to real fault detection. At equal suite size, the correlation was weak, around 0.05 to 0.20. Even so, the top 10% of suites by mutation score found more faults than random suites of the same size. The lead was 11% for the Java faults and 46% for the C faults.

Chekam and colleagues call the procedure described so far strong mutation. For suites made up of 7.5% of their test pool, the top 10% by that criterion found about 13% more faults than random suites of the same size. Papadakis and colleagues conclude that the score helps when improving a suite but poorly reflects its actual effectiveness. A surviving mutant thus points to a concrete gap, while the score alone is not a measure of quality.

Gating on diff coverage

In the example, main contains legacy code without a test, the method ApplySurcharge. A gate on overall coverage then fails on every PR:

> codecharter coverage --min-coverage 100
…
Line coverage 50% is below the required minimum of 100% (source: cli-flag).
Coverage: 1/2 lines = 50% (required 100%, source: cli-flag). 1 uncovered region(s) in 1 file(s). Test projects: 1 passed, 0 failed. See 'uncoveredRegions' in the report for exact lines and snippets.

The run ends with exit code 1. Under uncoveredRegions, the JSON report names the file, method and line. Without --min-coverage and without configuration, 100% is the minimum as well.

Diff coverage measures only the lines that the PR changes. The branch feature/rounding first adds ApplyDiscountRounded without a test:

> codecharter coverage --git-ref main..HEAD --min-diff-coverage 100
…
Diff coverage 0% (0/1 changed lines) for the git range 'main..HEAD' is below the required minimum of 100% (source: --min-diff-coverage).
Diff coverage: 0/1 changed lines = 0% (required 100%, source: --min-diff-coverage, git ref: main..HEAD). 1 uncovered changed region(s) in 1 file(s). Overall: 1/3 lines = 33.33% (not gated). Test projects: 1 passed, 0 failed. See 'diffCoverage.uncoveredChangedRegions' in the report for exact lines and snippets.

The run ends with exit code 1. With the test that expects 16.99, the same call passes with exit code 0:

…
Diff coverage: 1/1 changed lines = 100% (required 100%, source: --min-diff-coverage, git ref: main..HEAD). 0 uncovered changed region(s) in 0 file(s). Overall: 2/3 lines = 66.66% (not gated). Test projects: 1 passed, 0 failed.

On the same state, the overall gate reports 66.66% and exit code 1. The diff gate requires a test to execute every piece of new code, and the legacy code does not block the PR. If a solution has hardly any legacy code and its overall coverage is already at the threshold, the overall gate alone is enough.

With --git-ref, the diff gate alone decides. If the call also passes --min-coverage 100, CodeCharter reports the overall number as not gated and, in the example, ends with exit code 0 despite 66.66%. If overall coverage should have a lower bound as well, a second call follows. With --skip-tests, it evaluates the files from the first run, in the example in 1.7 seconds:

codecharter coverage --git-ref origin/main..HEAD --min-diff-coverage 100
codecharter coverage --skip-tests --min-coverage 60

The lower bound of 60% sits just below the current state. In CI, origin/main..HEAD needs the base commit in the clone, in GitHub Actions for example through fetch-depth: 0. If it is missing, the run ends with exit code 64. The documentation for codecharter coverage describes all options.

Failing tests and missing data

If a test fails, CodeCharter does not evaluate the coverage:

> codecharter coverage --min-coverage 100
…
Test project 'Shop.Tests' failed (exit code 1).
  Failed test: Shop.Tests.PriceCalculatorTests.TenPercentDiscountReducesOneHundredToNinety
    Assert.Equal() Failure: Values differ
    Expected: 91
    Actual:   90,00
…
At least one test project failed; coverage was not gated.
…

The run ends with exit code 2, even if the measured coverage would reach the threshold. If a passing test project produces no coverage file because coverlet.collector is missing, the run also ends with exit code 2:

Test project 'Shop.Tests' passed but produced no coverage file. The 'XPlat Code Coverage' collector requires the coverlet.collector package. Add <PackageReference Include="coverlet.collector" Version="6.*" PrivateAssets="all" /> to '…\tests\Shop.Tests\Shop.Tests.csproj'.
At least one test project failed; coverage was not gated.

According to CodeCharter's documentation and code, the same applies to a referenced project that coverlet did not instrument, for example because of a missing PDB file. The report then lists it under uninstrumentedModules.

One gap remains. CodeCharter expects data only for projects that a test project references. The branch feature/billing creates a new project Shop.Billing that no test project references:

> codecharter coverage --git-ref main..HEAD --min-diff-coverage 100
…
Diff coverage gate passed: the git range 'main..HEAD' changed no measurable lines.
Diff coverage: no measurable changed lines in git ref 'main..HEAD' (gate passed). Overall: 1/2 lines = 50% (not gated). Test projects: 1 passed, 0 failed.

The diff gate passes with exit code 0 and without a warning, and Shop.Billing does not count toward the overall number either. For a new project, the review therefore checks whether a test project references it.

Using mutation testing

In the example, Stryker took 13 to 24 seconds for two to five mutants, largely for the build and the initial test run. In a real solution, the run time grows with the number of mutants and the duration of the tests. A person assesses every surviving mutant: is a test missing, or does the mutation affect behavior that no requirement specifies?

The Microsoft documentation on mutation testing advises against aiming for a mutation score of 100%. It recommends focusing on high-risk and business-critical areas. Applied to code, that means classes whose faults are expensive, such as pricing, tax or authorization logic. For code that only passes data along or maps it, surviving mutants that do not reveal a missing requirement are more likely. The example does not measure this.

For the example, this means that every PR gets the diff gate at 100% and the lower bound for overall coverage. PriceCalculator additionally gets a Stryker run, because a wrong price is expensive and the run found the weak test and the half-covered ternary. It runs on every PR that changes PriceCalculator, and the review reads the report. Which tests a PR has to run is covered in the article on selecting affected test projects in .NET. The article on code quality in CI pipelines shows how to integrate this into the pipeline.