【问题标题】:JUnit test IndexOutOfBoundsExceptionJUnit 测试 IndexOutOfBoundsException
【发布时间】:2020-02-18 21:46:20
【问题描述】:

当索引超出范围时,我的方法 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


    【解决方案1】:

    验证此行为的正确方法取决于您使用的是 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()));
    

    【讨论】:

    • 我正在使用 JUnit 4。不幸的是,它不适用于添加 @Test(expected = IndexOutOfBoundsException.class) 并且我认为自 JUnit 测试以来我必须更改 get(int index) 方法中的某些内容代码已经给我了。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2020-07-26
      • 2020-04-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多