JUnit测试IndexOutOfBoundsException

问题描述 投票:0回答:2

当索引超出范围时,我的方法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");
    }
}
java junit indexoutofboundsexception
2个回答
0
投票

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

对于JUnit 4,您用预期的异常注释了您的测试方法:

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

JUnit 5使用assertThrows,如下所示:

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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.