JUnit test IndexOutOfBoundsException - PullRequest
       7

JUnit test IndexOutOfBoundsException

0 голосов
/ 19 февраля 2020

У меня проблема с моим методом get (int index), когда 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");
    }
}

Ответы [ 2 ]

0 голосов
/ 19 февраля 2020

Вместо использования блока try-catch в тестах JUnit просто добавьте аннотацию теста. Обновите @Test до @Test(expected = IndexOutOfBoundsException.class.

0 голосов
/ 19 февраля 2020

Правильный способ проверки этого поведения зависит от того, используете ли вы 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()));
...