TestNG : Expected Exception Test

It is always good to test the working and output of your unit. But it is more important to test the negative behavior to make application robust. What if you are expecting an exception from a part of code which is not thrown. the point where application has to get terminated, it is moving smoothly to get a dead lock or a pitty crash. Just to save such situation Testing of exception generation is code is very important. There are annotation in TestNG frame work which helps to make is an easy task.

Example

import org.testng.annotations.*;

public class TestNGTest2 {

	@Test(expectedExceptions = ArithmeticException.class)  
	public void divisionWithException() {  
	  int i = 1/0;
	}  

}

In above example, the divisionWithException() method will throw an ArithmeticException Exception, since this is an expected exception, so the unit test will pass.

More advanced example can be observed in the snap shot attached.
Where the scenarios to test says – “Calling this method with null argument throws Exception”.
The test will go green if exception is thrown, else it will go red.

Testing the expected exception

Testing the expected exception

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s