javaiteratorjunit4listiterator

How to write JUnit test for ListIterator in java to test if the listiterator has been set to a specific index


Im trying to write a code which can set the beginning of my Iterator to a specific index, and this method must create and return an object that implements ListIterator and is located in this linkedlist just prior to the node at the location corresponding to index.

Here's the method I wrote, but I dont know how to write the Junit test code to test my method, it will always show me Stack Over flow. The method should return a ListIterator that begins at index.

Method:

public ListIterator<E> listIterator(int index) {
    ListIterator <E> myIter = listIterator();
    if ( index < 0 || index > size) {
        throw new IndexOutOfBoundsException();
    }
    else {
        for ( int i = 0; i < index && myIter.hasNext(); i++) {
            myIter.next();
        }

    }
    return (ListIterator<E>) myIter;
}

JUnit test: public class KWLinkedListTest extends TestCase{

private KWLinkedList <String> myList;

@Before
public void setUp() throws Exception {

    myList = new KWLinkedList<String>();
    myList.add("Top");
    myList.add("Mid");
    myList.add("Jg");
    myList.add("Sup");
    myList.add("Adc");
    ListIterator <String> myIter = myList.listIterator();


}

@Test
public void testlistiterator() {

    myList.listIterator(2);
    assertEquals(myList.next(),"Mid");
}

Solution

  • I ran into difficulties reproducing your issue in a test project using the code you provided.

    ListIterator <E> myIter = listIterator(); is calling itself without a required argument. Even if the argument were provided, this would result in infinite recursion / stack overflow.

    size is an unrecognized symbol.

    The code for the type KWLinkedList is missing.