1

I am practicing with JUnit, this is the simple method I want to test

public float divide(int a, int b){
      return (float)a/(float)b;
}

This is the test (Maths is just a custom class of mine containing that method):

@Test(expected = ArithmeticException.class )
public void divideByZeroShouldBeDetected(){
    Maths m = new Maths();
    m.divide(2,0);
}

Anyway running this test results into a fail...

edit: ok just checked something "strange", this code actually gives me the exception:

float c = 2/0;

anyway this one:

m.divide(2,0);

gives me

Infinity

and that's the reason why the test fails. So..how to test this behaviour in Junit?

Phate
  • 6,066
  • 15
  • 73
  • 138

3 Answers3

3

Ok solved....problem was about the type of the paramethers, in this post you can find a complete explaination Java division by zero doesnt throw an ArithmeticException - why?.

In order to make a Test I just had to assert the returned value was "infinite", this way:

@Test
public void divideByZeroShouldBeDetected(){
    Maths m = new Maths(2, 0);
    assertEquals("divide float by zero should be infinity", true, Float.isInfinite(m.divide()));
}
Community
  • 1
  • 1
Phate
  • 6,066
  • 15
  • 73
  • 138
2

And also,

To clarify, ArithmeticException is thrown only for integers and not for floats.

package com.ey.buildmap;
public class test
{
    public static void main(String[] args) {
        try
        {
            //System.out.println(3/0);
            System.out.println((float)5/(float)0);
        }
        catch(ArithmeticException e)
        {
            e.printStackTrace();
        }
    }
}

I mean, in the above example, System.out.println(3/0); will throw ArithmeticException, whereas the next line won't as the result will be Infinity.

maddy
  • 19
  • 1
1

I think your divide method inside Maths class is not correct to pass this test case.

because float number divisible by either 0 or 0.0 is always Infinity.Hence you will never get Arithmetic exception.

dReAmEr
  • 6,986
  • 7
  • 36
  • 63