Home > OS >  Test cases needed for 100% coverage
Test cases needed for 100% coverage

Time:12-21

I'm writing UT for this if condition:

if (a != null && a.x != null && a.y != null) {
//do things
}

Sonar says that it needs 6 cases to be covered 100% and my code already covered 4. enter image description here I want to now all the test cases here (6) to get 100% coverage

CodePudding user response:

Based on the code that you have given I can see one test case for each of the following conditions -

  1. a==null
  2. a!=null && a.x==null
  3. a!=null && a.y==null
  4. a.x=valid value
  5. a.y=valid value

The '//do things' part may contain logical decisions which may require additional tests. This is where probably the 6th test case is being identified by sonar.

CodePudding user response:

Sonarqube defines "condition coverage" like so...

Condition coverage (branch_coverage): On each line of code containing some boolean expressions, the condition coverage answers the following question: 'Has each boolean expression been evaluated both to true and to false?'. This is the density of possible conditions in flow control structures that have been followed during unit tests execution.

There's two problems.

  1. Condition coverage and branch coverage are different. Your code has just two branches.
  2. You have to test all combinations in a condition.

All they seem to care is that each part has been true and false at least once: a is null, a is not null, a.x is null, a.x is not null, a.y is null, a.y is not null. Maybe that's how they got six?

But that is not condition coverage. You can do it in two passes, everything true, and everything false.

You need to test every combination of a, a.x, and a.y being null and not null. This would be 2^3 or 8.

However, a false will short circuit the && operator so there's no need to go further once you hit a false.

a != null a.x != null a.y != null
F any any
T F any
T T F
T T T

That's four.

  • Related