Junit Tutorial – Expected Exception Test

Junit doesn’t only intend to ensure that code is working as expected and validate that this is still the case after code changes, it’s also capable for testing method which expects to throw desired exception.

Two ways are available in Junit to test expected exception.

1. Catch the exception and assert success, if this exception was not thrown then assert fail

@Test
public void testIndexOutOfBoundsException() {
  try {
    System.out.println("test :: IndexOutOfBoundsException");
    List list = new ArrayList();
    list.get(1);
    fail("There should throw IndexOutOfBoundsException");
  } catch (IndexOutOfBoundsException e) {
    //There should do something validate  excpetion
    assertEquals(e.getMessage(),  "Index: 1, Size: 0");
  }
}

2. Use Junit test expected exception annotation

@Test(expected = IndexOutOfBoundsException.class)
  public void testIndexOutOfBoundsException() {
  System.out.println("test :: IndexOutOfBoundsException");
  List list =  new ArrayList();
  list.get(1);
}

We didn’t add an element to the list,  so list.get(1) thrown  IndexOutOfBoundsException, this was an expected Exception, the test should pass.

Оцените статью
ASJAVA.COM
Добавить комментарий

Your email address will not be published. Required fields are marked *

*

code