0

I need to implement the Division by Zero operation in a method such that (1) ​every​ test suite that achieves 100% path coverage reveals the fault and (2) it is ​possible​ to create a test suite that achieves 100% branch coverage and does ​not​ reveal the fault.

As division by zero is very simple operation,I would like to know the implementation of this method such that these two requirements can be met.Currently, I am not able to do it because my branch and path coverage test cases both reveals a fault(ArithmeticException) and are same.

This is my current code but it is wrong.

void method1(int m, int n)
         int p = m / n;
         if (n != 0) {
         System.out.println("Print some value");
         }
         if (n == 0) {
         System.out.println("Infinity");
         }
         return p;

Thanks

user3624146
  • 369
  • 1
  • 5
  • 16

2 Answers2

1

Well, it's just an exercise I guess, so one could do something extremely dumb, like this:

double method1(int m, int n) {
     double p;
     if (n >= 0) {
         p = m / n;
     } else {
         p = m / n;
     }

     if (n > 0) {
         p = m / n;
     } else {
         p = m / n;
     }

     return p;
}

In that manner, if you have full path coverage, then you must have covered the path of going into n >= 0 branch in the first condition and going into n <= 0 branch in the second one. So EVERY 100% path coverage suite must use n = 0 in some test case and that throws an ArithmeticException as it did in your code, so faultiness of the method is revealed.

On the other hand, you only require, say, n = 1 and n = -1 test cases to achieve full branch coverage (dumb test suite, admittedly), but you completely miss zero division part. I did not test this, however.

  • Not sure if you edited this or what, but the code above does not match your comment - there is no `n <= 0` case, just `n > 0 and n >= 0` the first of which obviously is not true when `n = 0` and thus wouldn't be executed. – Bricky Oct 30 '21 at 19:35
  • By "`n <= 0` branch in the second (condition)" I meant the `else` branch. To cover path consisting of `if` branch in 1st condition and `else` branch in 2nd condition one must use `n = 0`. – Jakub Łanecki Nov 05 '21 at 05:21
-1

Check for the divisor equal 0 first and either return or throw an exception. Waiting to get a divide by 0, when you know it is a real possibility, is not a good practice.

Steve11235
  • 2,849
  • 1
  • 17
  • 18
  • int c = 0; if (b == 0) { System.out.println("Sorry. That's an DiviDeByZeroException"); } else c = a / b; return c; Even if I do it in this way, My branch and path coverage are coming to be same. How can I make sure that branch coverage does not through an Exception while path coverage does? – user3624146 Mar 29 '18 at 19:05