JUnit – Expected Exception Test

Junit provides a way to test whether code throws desired exception or not. Following example demonstrates Excepted Exception Test using JUnit.

First create a new Java Project and configure it as Maven Project. For Reference, Click Here

Add the following dependencies in pom.xml

  <dependencies>
   	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.10</version>
	</dependency>
  </dependencies>

Test Passed

Create following class

package com.kruders.junit;

import org.junit.Test;

public class JunitExpectedExceptionTest {
	@Test(expected = ArithmeticException.class) 
	public void testDivide(){
		int result = 10 / 0;
	}
}

Now when you run the project, following screen will be displayed. The testDivide() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.

Figure 3.1 Figure 3.1

Test Failed

Create following class

package com.kruders.junit;

import org.junit.Test;

public class JunitExpectedExceptionTest {
	@Test(expected = IndexOutOfBoundsException.class) 
	public void testDivide(){
		int result = 10 / 0;
	}
}

Now when you run the project, following screen will be displayed. The testDivide() method will throw an ArithmeticException Exception, but expected exception is IndexOutOfBoundsException, so the unit test will fail.

Figure 3.2 Figure 3.2

No comments yet.

Leave a Reply