Programming, Quality, Tests, Unit tests

Unit tests: code coverage – line coverage vs branch coverage

Quite often we can meet with a statement that code coverage should be x% where usually x = 80. But what is exact meaning? Is it line coverage or branch coverage or something else? Typicaly developers are using line coverage as most of software supports it however much more meaningful is branch coverage. Let’s take a look into following method example:

public bool GetSomething(int? value)
{
   if(!value.HasValue())
   {
      return false;
   }
   else
   {
      return true;
   }
}

Above example is quite simple – we have 2 cases to handle which we can handle with 2 tests, so for this method line coverage will be 100%.

Now let’s see a bit modified example

public bool GetSomething(int? value)
{
   if(!value.HasValue() || value == 0)
   {
      return false;
   }
   else
   {
      return true;
   }
}

Above example is quite simple – we have 3 cases to handle. I we would use the same test suit as above, we ould have 100% line coverage but only 66.6(6)% branch coverage. The additional test case – when value is equal to 0 causes this difference. If we will add one more test, we will have the same branch coverage (100%). Right now, try to imagine how many of such situations you have in your code and how significant will be the difference between line coverage and branch coverage in bigger project.

Therefore my recommendation is to to follow branch coverage and also never treat code coverage as KPI. Otherwise you will get crazy as in some projects such coverage like I mentioned at the beginning (80%) is not achievable. Just keep reasonable in what you test and how you test. If you cannot test something with unit tests, use integration tests.

Leave a Reply

Your email address will not be published.