JUnit test exception handling
Exception handling in JUnit tests refers to testing if a particular piece of code throws an expected exception under certain conditions.
To test exception handling in JUnit, you can use the @Test
annotation with the expected
attribute set to the expected exception. The test method should then be written to cause the expected exception to be thrown. Here's an example:
import org.junit.Test;
public class ExceptionTest {
@Test(expected = ArithmeticException.class)
public void divideByZeroTest() {
int x = 5 / 0;
}
}
In this example, the divideByZeroTest
method is expected to throw an ArithmeticException
, which is the exception that is thrown when you try to divide by zero. The test will pass if the exception is thrown, and fail if it is not thrown or if a different exception is thrown.
You can also test for exceptions in JUnit using a try-catch
block and using the fail()
method to indicate a failure if the expected exception is not thrown. Here's an example:
import org.junit.Test;
public class ExceptionTest {
@Test
public void divideByZeroTest() {
try {
int x = 5 / 0;
fail("Expected ArithmeticException not thrown");
} catch (ArithmeticException e) {
// expected exception was thrown, test passed
}
}
}
try
block is expected to throw an ArithmeticException
. If the exception is thrown, the test will pass because the catch
block will be executed. If the exception is not thrown, the fail
method will be called, indicating that the test has failed.Leave a Comment