Reputation: 193
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 = .. )
Upvotes: 2
Views: 1999
Reputation: 718798
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
x
to a float
((float) x) / y
computation using floating point arithmetic When you remove the cast:
return x/y;
means
x/y
computation using integer arithmeticSo there are actually a number of (potential) conceptual errors that might have lead to the mistake that you made.
/
.int
and a float
is performed using 32 bit floating point arithmetic. (The int
operand will be widened to a float
)return
statement is an assignment context.Upvotes: 7