Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test case for 100% branch coverage with no fault?

The problem statement is

A method that has a zero fault that you can write a test suite to that has 100% statement coverage but doesn't find the fault and another test suite that has 100% branch coverage that does reveal the fault?

Here is the method I wrote for the same

public  faultyMethod1(int x, int y) {
  int X =x;
  int Y = y;

  if (Y !=0){
    Z = X/Y;
  } else {
    System.out.println("Sorry. That's an DiviDeByZeroException");
  }
}

faultyMethod1 (1,2);
faultyMethod1 (2,0);

The above code to achieve test suite that has 100% branch coverage that does reveal the fault"

What about test suite to that has 100% statement coverage but doesn't find the fault ?

like image 262
Suresh Atta Avatar asked Nov 05 '15 03:11

Suresh Atta


Video Answer


1 Answers

Let's make another example...

// The method, according to our imaginary specification, should do:
//  return x * y, IF x is less than 2
//  return x + y, in any other case
public int doSomething(int x, int y) {

if (x < 2 ) {
   return x * x;  // this is our bug, it SHOULD be x * y
}

return x + y;

}

Now imagine we have two tests:

assertEquals(0, doSomething( 0, 12) );  // works, as 0 * 0 == 0 * 12
assertEquals(20, doSomething( 10, 10 ) ); // works fine

So, now we have 100% test coverage (because the x < 2 branch has been covered, as well as the other one). But we didn't find the bug, since using zero as value for x hides it (since 0 * something is always 0, y is irrelevant). We would have needed something like this...

assertEquals(12, doSomething( 1, 12) );  // fails, because it will be 1*1 == 1

The same problem can occur for any other situation, including a division by zero. Can't imagine a good example, but I guess you get the basic idea how having a 100% coverage does not mean finding 100% of all bugs. (A cool way to find them would be mutation testing, but that's a pretty advanced topic.)

like image 90
Florian Schaetz Avatar answered Oct 29 '22 21:10

Florian Schaetz