I am trying to test the functionality of dividing by zero.
If I just do: System.out.println(5/0)
, I will get java.lang.ArithmeticException
I am trying to test that the exception was thrown.
Here's my unit test:
@Test(expected = ArithmeticException.class)
public void given_divideByZeroInput_when_divideByZero_then_verify_throwing_exception() {
MathClass sut = new MathClass();
sut.div(10,0);
}
and my div
is this simple:
public float div(int x, int y) {
return (float) x/y;
}
However, the unit test is failing, stating:
java.lang.AssertionError: Expected exception: java.lang.ArithmeticException
What did I do wrong?
I know there are many ways to test the thrown exception, but I am trying to stick with the simple @Test(excepted = .. )
JB Nizet has found the answer:
You're casting x to a float. Thus you're not doing integer division as you're doing in your first snippet, but float division. And the result is thus Infinity, not an exception.
But there is something more to explain:
return (float) x/y;
means
- convert
x
to afloat
- perform the
((float) x) / y
computation using floating point arithmetic - return the value
When you remove the cast:
return x/y;
means
- perform the
x/y
computation using integer arithmetic - convert the value to a float (implicitly!)
- return the value
So there are actually a number of (potential) conceptual errors that might have lead to the mistake that you made.
- A type cast has a higher precedence than
/
. - An arithmetic operation involving an
int
and afloat
is performed using 32 bit floating point arithmetic. (Theint
operand will be widened to afloat
) - Widening also happens in an "assignment context", and a
return
statement is an assignment context.