All Posts

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”

 

JUnit Exception Test

 

That’s it.