JUnit
– Exceptions Test
JUnit
provides a option of tracing the Exception handling of code. You can
test the code whether code throws desired exception or not.
The
expected parameter is used as follows @Test(expected)
.
Below
simple example explain how the @Test(expected) works in Junit.
import
org.junit.Test;
import
org.junit.runner.JUnitCore;
import
org.junit.runner.Result;
import
org.junit.runner.notification.Failure;
public
class
ExceptionTest {
@Test(expected
= ArithmeticException.class)
public
void
divisionWithException() {
int
i =
1/0;
}
/**
* @param
args
*/
public
static
void
main(String[] args) {
Result result = JUnitCore.runClasses(ExceptionTest.class);
for
(Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}