Friday, August 29, 2014

JUnit Exception Testing

In Automation, it is not only important to check if screens behave as expected with correct data, it is also important to check if tests would throw exception when invalid/inappropriate data is given, this will make the Framework more robust

Lets see how JUnit allows us to do Excepton Testing

Example 1

new ArrayList<Object>().get(0); // Array list is empty, so it should result in IndexOutOfBoundsException

  @Test(expected= IndexOutOfBoundsException.class)
    public void empty() {
         new ArrayList<Object>().get(0);
    }
So this test case would pass, if IndexOutOfBoundsException is thrown else the Test case fails

Example 2

 @Test
    public void testExceptionMessage() {
        try {
            new ArrayList<Object>().get(0);
            fail("Expected an IndexOutOfBoundsException to be thrown");
}

         catch (IndexOutOfBoundsException anIndexOutOfBoundsException) {
            assertThat(anIndexOutOfBoundsException.getMessage(), is("Index: 0, Size: 0"));
            }
    }

In this way we can not only test what Exception we get but we can also validate what message is thrown 

No comments:

Post a Comment