JUnit exception testing

Now a days while I discover TDD and testing in software development, I’ve come to realize that it is also possible to test exceptions in Junit as well. I’ve noticed this while I was checking a code snippet of a software online and right after that I’ve tested the same thing to see the outcome. Simply to demonstrate the way of it, I’ll write a sample code snipped for you to easily and carefully study.

The test will be conducted using Junit version 4 and preferred IDE is IntelliJ.

@Test(expected = IndexOutOfBoundsException.class)
    public void exceptionTestCase() {
        //Create a list with simple dummy data
        List<String> myList = Arrays.asList("A", "B", "C");

        assertNotNull("The corresponding object is not null",myList);

        assertEquals("The collection has three elements",3, myList.size());

        //Cause the collection to throw an IndexOutofBoundException
        myList.get(Byte.MAX_VALUE);

    }

Here in the @Test annotation we first of all write our expected exception which will be throw by the candidate method. As you see there is no assert method being implemented.On the other hand you’ll see that the code has successfully passed the test

Leave a Reply

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