Sloshy
Sloshy

Reputation: 45

Junit implements Iterable

I am trying to do tests on a class that implements Iterable. When I go to test any method,in the itorator class, like hasNext(), next(). So when I call list.itorator().Next(); nothing happens, the node is the current node in the list not the next. but when I do ListIterator itrList = new ListIterator(list); the code inside it works. I am calling public Iterator iterator() {return new ListIterator (this); So what am I not doing correctly/ grasping? Thanks for any help.

public void test6() {
    List<String> list = new List<String>();

    list.addAfterCurrent("1");
    list.addAfterCurrent("2");
    list.addAfterCurrent("3");
    ListIterator itrList = new ListIterator(list);


    TextIO.putln(list.iterator().next()); // output is 1
    TextIO.putln(list.iterator().next()); // output is 1 
    TextIO.putln(itrList.next());         // output is 1
    TextIO.putln(itrList.next());         // now output is 2           
    assertEquals("1", list.getCurrent());
    assertEquals(3, list.size());

}

Upvotes: 1

Views: 1520

Answers (2)

Jim Garrison
Jim Garrison

Reputation: 86774

You are creating a new iterator every time and starting over at the beginning.

Upvotes: 0

Louis Wasserman
Louis Wasserman

Reputation: 198033

You're creating a fresh iterator each time you call list.iterator(). You want to keep the same iterator and call its next method multiple times, e.g.

Iterator itr = list.iterator();
assertEquals(1, itr.next());
assertEquals(2, itr.next());

Upvotes: 7

Related Questions