I've got the following iterable changes
(don't ask why it's not in my control). And I want to ensure there are specific items in the changes
and I used the following:
Iterable<ChangedValue> changes = record.getValues();
assertEquals(2, Iterables.size(changes));
changes.forEach(entry -> {
if (entry.getName().equals("Title")) {
assertEquals("old name", entry.getFrom());
assertEquals("new name", entry.getTo());
} else if (entry.getName().equals("Description")) {
assertEquals("old description", entry.getFrom());
assertEquals("new description", entry.getTo());
}
});
The problem with the above is that the above test case passes if the 2nd "change" is something else other than "Description". If changes
was a list I would've done something like:
assertEquals(2, changes.size());
assertEquals("Title", changes.get(0).getName());
assertEquals("old name", changes.get(0).getFrom());
assertEquals("new name", changes.get(0).getTo());
assertEquals("Description", changes.get(1).getName());
assertEquals("old description", changes.get(1).getFrom());
assertEquals("new description", changes.get(1).getTo());
So my question is, how can I achieve assertions similar to the above with an iterable?
CodePudding user response:
Use an explicit Iterator
:
Iterator<ChangedValue> changes = record.getValues().iterator();
assertTrue(changes.hasNext());
ChangedValue change = changes.next();
assertEquals("Title", change.getName());
assertEquals("old name", change.getFrom());
assertEquals("new name", change.getTo());
assertTrue(changes.hasNext());
change = changes.next();
assertEquals("Description", change.getName());
assertEquals("old description", change.getFrom());
assertEquals("new description", change.getTo());
assertFalse(changes.hasNext());