Expected / Unexpected Exception Test

Expected Exception Test
Add the optional expected attribute to the @Test annotation. The test will pass when the expected exception thrown.
Check the below example
  
import org.junit.Test;


public class ExceptionTestDemo {

 String str;
 
 @Test(expected = NullPointerException.class)
 public void testNullPointerException() {
  str.toLowerCase();
  
 }

}
The result will be "pass" because the method thrown expected exception (NullPointerException)

Unexpected Exception Test
Declare the exception in the throws clause of the test method and don't catch the exception within the test method. Uncaught exceptions will cause the test to fail with an error.
  
import org.junit.Test;


public class ExceptionTestDemo {

 String str;
 
 @Test
 public void testNullPointerException() throws NullPointerException {
  str.toLowerCase();
  
 }

}
Above example test that fails when the NullPointerExceptoin is thrown

Prev:Template for Junit                                                                            Next:Creating Test Suite in Eclipse

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...