JUnit test IndexOutOfBoundsException



当索引越界时,我的方法get(int index(有问题。我不知道如何以正确的方式抛出异常以通过下面的测试。

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();
}

我的JUnit测试代码:

/**
* 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");
}
}

验证此行为的正确方法取决于您使用的是JUnit 4还是5。

对于JUnit4,您用预期的异常来注释测试方法:

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

JUnit 5使用assertThrows,如下所示:

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

不要在JUnit测试中使用try-catch块,只需添加到测试注释中即可。将@Test更新为@Test(expected = IndexOutOfBoundsException.class

最新更新