Blog
JUnit Exception Test
JUnit Exception Test
In this tutorial, you will learn about JUnit Exception test. In JUnit we use “expected” with @Test annotation and specify the type of exceptions that are expected to be thrown when executing the test methods.
Example
@Test(expected=ArithmeticException.class)
public void dividedByZeroExample(){
int result = 1/0;
}
A sample example which throws an exception called âArithmeticExceptionâ when dividing two numbers with denominator value as 0.
If we remove the â(expected = ArithmeticException.class)â, it will return exception called âjava.lang.ArithmeticException: / by zeroâ
Sample Test
import org.junit.Test;
public class JUnitExample {
@Test(expected=ArithmeticException.class)
public void dividedByZeroExample1(){
int e = 1/0;
}
@Test
public void dividedByZeroExample2(){
int e = 1/0;
}
}
When we execute the above code, the test method “dividedByZeroExample1” will return as âPassedâ as we are handling the exceptions and the Test Method “dividedByZeroExample2” will return output as “Failed” with exception as ‘âjava.lang.ArithmeticException: / by zeroâ

That’s it.