teak
teak

Reputation: 23

how to assert nested lists using hamcrest java

I have some nested lists I would like to assert using hamcrest. Basically they are lists of items contained in a list.

e.g.

List<List<String>> [[bed, bench, bookshelf], [book, bowl, basket], [bar, biscuit, smoked beef]]

I would like to assert that every item starts with "b"

hasItem seems to stop matching after the first list.

assertThat(list, hasItem(everyItem(startsWith("b"))));

How can I do this in hamcrest?

I have tried contains as well.

Thanks...

Upvotes: 2

Views: 2476

Answers (2)

Roland Weisleder
Roland Weisleder

Reputation: 10511

hasItem checks if there is atleast one item with the given condition. Your first inner list fulfills the condition, so hamcrest will stop.

As you figured out, everyItem checks .. every item.

Solution: assertThat(list, everyItem(everyItem(startsWith("b")))); To please the compiler you have to cast List<List<String>> to Iterable<Iterable<String>> list

Upvotes: 1

GhostCat
GhostCat

Reputation: 140457

My gut feeling is that you won't get there by using existing matchers.

But writing your own matcher ... takes only a few minutes, once you understand how things come together.

Maybe you check out another answer of mine; where I give a complete example how one can write his own matcher. Back then, that took me maybe 15 minutes; although I had never written custom matchers before.

Upvotes: 1

Related Questions