Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to JUnit test a iterator

For example, how do I test:

ArrayList<String> list = new ArrayList<String>();
list.iterator();

How to test this "iterator()" method?

Thanks.

like image 329
JJ Liu Avatar asked Feb 17 '13 10:02

JJ Liu


2 Answers

The few tests I can think of are:

  • test hasNext on an empty collection (returns false)
  • test next() on an empty collection (throws exception)
  • test hasNext on a collection with one item (returns true, several times)
  • test hasNext/next on a collection with one item: hasNext returns true, next returns the item, hasNext returns false, twice
  • test remove on that collection: check size is 0 after
  • test remove again: exception
  • final test with a collection with several items, make sure the iterator goes through each item, in the correct order (if there is one)
  • remove all elements from the collection: collection is now empty

You can also have a look at the tests used in openJDK.

like image 71
assylias Avatar answered Sep 24 '22 14:09

assylias


You don't.

Guys from oracle and sun have already done that.

If you create your own implementation of iterator then you have to implement AFAIR 2 methods and you have to check if they obey to the contract.

Now that means: returning next element of underlying collection or throwing an exception and telling if there are subsequent elements. Just call those methods on your iterator and assert the result.

like image 25
piotrek Avatar answered Sep 22 '22 14:09

piotrek