Home » Java » java – JUnit test IndexOutOfBoundsException-Exceptionshub

java – JUnit test IndexOutOfBoundsException-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a problem with my method get(int index) when index is out of bounds. I do not know how to throw the exception in a correct way in order to pass the test below.

    public E get(int index) throws IndexOutOfBoundsException {

    Node<E> tempNode = head;
    for (int i = 0; i < index; i++) {
        if (index < 0) {
            throw new IndexOutOfBoundsException();
        }
        if (index > size) {
            throw new IndexOutOfBoundsException();
        }

        tempNode = tempNode.getmNextNode();
    }
    return tempNode.getmElement();
}

My JUnit test code:

/**
 * Create a single linked list containing 5 elements and try to get an
 * element using a too large index.
 * Assert that an IndexOutOfBoundsException is thrown by the get() method.
 */
@Test
public void testGetByTooLargeIndexFromListWith5Elements() {

    int listSize = 5;
    // First create an ArrayList with string elements that constitutes the test data
    ArrayList<Object> arrayOfTestData = generateArrayOfTestData(listSize);
    // Then create a single linked list consisting of the elements of the ArrayList
    ISingleLinkedList<Object> sll = createSingleLinkedListOfTestData(arrayOfTestData);

    // Index out of range => IndexOutOfBoundException
    try {
        sll.get(sll.size());
    }
    catch (IndexOutOfBoundsException e) {
        System.out.println("testGetByTooLargeIndexFromListWith5Elements - IndexOutOfBoundException catched - " + e.getMessage());
        assertTrue(true);
    }
    catch (Exception e) {
        fail("testGetByTooLargeIndexFromListWith5Elements - test failed. The expected exception was not catched");
    }
}
How to&Answers:

The proper way to verify this behavior depends on if you are using JUnit 4 or 5.

For JUnit 4, you annotate your test method with the expected exception:

@Test(expected = IndexOutOfBoundsException.class)
public void testGetByTooLargeIndexFromListWith5Elements() {...}

JUnit 5 uses assertThrows, like so:

org.junit.jupiter.api.Assertions
  .assertThrows(IndexOutOfBoundsException.class, () -> sll.get(sll.size()));

Answer:

Instead of using a try-catch block in JUnit tests, just add to the test annotation. Update @Test to @Test(expected = IndexOutOfBoundsException.class.