Reputation: 378
How do i test for the equality of two iterators using JUnit?
Is there any built in method or is it just by comparing each and every element in that?
Thanks, Sriram
Upvotes: 4
Views: 5699
Reputation: 2375
There is no "classical" notion of equality for Iterator
s except for object identity, because they are mutable in the "worst" kind of way.
In a JUnit scenario, it would probably be preferable to collect the values next()
returns into a list, e.g. using Guava's ImmutableList.copyOf(Iterator<T>)
, and then proceed with assertThat(a, is(b))
as described in this SO answer
Upvotes: 1
Reputation: 116246
You can't (and needn't) test the equality of iterators, only that of the underlying collections. To do that, you can iterate through both and compare each pair of elements in turn, as you guessed. Note that this effectively consumes at least one of the iterators. And the result is dependent on the state of the iterators at the start of the test, so this method is brittle. Therefore it is best to get hold of the underlying collections and test them directly for equality (using their equals
method), whenever you can.
Why would you ever want to test the equality of two iterators? If you explain your concrete problem, we may be able to offer a better alternative.
Upvotes: 5
Reputation: 9587
There is no sane way to test equality of Iterator
s.
If going insane in this is an option, you may want to delve into the implementation of the specific iterator type you are testing, and use reflection to access private stuff and compare that (I'm sure, with enough analysis of source code, that you would find what needs to hold for two ListIterators to be equal, for example).
Or if it's your own iterator type, then export some variables that help you out and use them instead of reflection.
Iterating through and comparing elements is only a weak guarantee, as you could be iterating over a clone of your collection, meaning the iterators look the same, but aren't.
Just don't do this.
Upvotes: 1