Java Reference
In-Depth Information
Listing A.6
Exception handling the old 3.x way
public void
testDivisionByZero() {
Calculator c =
new
Calculator();
try
{
c.divide(5,0);
fail("Exception should have been raised, but was not");
}
catch
(ArithmeticException expected) {
assertTrue("Sanity check",
true
);
}
}
Basically, what you do is surround the troublesome code with a try-catch block
B
and
after that deliberately fail the test
C
if the exception was not thrown. A good practice
is also to place a dummy assert in the
catch
clause
D
just to make sure you always pass
through the
catch
clause.
In
JU
nit 4 we have a better solution for handling exceptional situations than we
had in
JU
nit 3. Every time you want to make sure that an exception is thrown, you can
use an
expected
parameter with the
@Test
annotation. Listing A.7 shows you how to
ensure that an
Arithmetic
exception is thrown.
B
C
D
Listing A.7
Exception handling with the expected parameter of the
@Test
annotation
[...]
public
class
CalculatorTest {
B
@Test(expected=ArithmeticException.
class
)
public
void
testDivisionByZero() {
Calculator c =
new
Calculator();
c.divide( 5, 0 );
}
}
As you can see in
B
, we've added the
expected
attribute to the
@Test
annotation to
denote that this method is supposed to throw an exception of the provided type.
A.3.6
Timeout testing
Another parameter you can add to the
@Test
annotation is the
timeout
parameter.
This feature was also missing in the “old”
JU
nit. With this parameter, you can specify a
value in milliseconds that you expect to be the upper limit of the time you spend exe-
cuting your test. What happens when the time runs out? An exception will be raised,
and the test will marked as failed, telling you that the test couldn't finish execution in
the given
Test
timeout
parameter. Listing A.8 shows you how to use the
timeout
parameter of the
@
annotation.