Exception Test in JUnit

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.

A below example which throws an exception called “ArithmeticException” when dividing two numbers with denominator value as 0.

@Test(expected=ArithmeticException.class)
	public void dividedByZeroExample1(){
		int e = 1/0;
	}

If we remove the “(expected = ArithmeticException.class)”, it will return exception called “java.lang.ArithmeticException: / by zero”

@Test
	public void dividedByZeroExample2(){
		int e = 1/0;
	}

Example: We will combine the above two examples and execute to check the output of the program

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”

Please find the below output of the above program.
exception test in Junit

Test Frameworks: 

Comments

hello,
thank you for publishing this tutorial. it's very helpful.

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.