Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the best way to assert items in an iterable

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading