Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...