shlogg · Early preview
Samuel Ko @samuelko123

Code Coverage: A Misleading Metric In C#

Code coverage measures execution, not logic. Example: `IsHuman` method has 100% coverage but still fails with order change. Writing good unit tests is more important than code coverage.

Introduction

Code coverage is an indicator, not an metric.
In this post, I will share an example for your entertainment.

  
  
  The code


public class Animal
{
    public bool CanTalk { get; init; }
    public bool CanWalk { get; init; }
}
public static class AnimalValidator
{
    public static bool IsHuman(Animal animal)
    {
        return animal.CanTalk && animal.CanWalk;
    }
}

    
    

    
    




  
  
  The good test

Let's test all the input combinations.
It gives us 100% code coverage:

public class AnimalValidatorTest
{
    [Theory]
    [InlineData(true, true)]
    public...