2

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...

teak
  • 23
  • 3

2 Answers2

1

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.

Community
  • 1
  • 1
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • ah thanks very much for the prompt response. yes i was considering that and/or stepping through each list with a for loop. I just thought there may be a 1 liner existing hamcrest matcher for nested lists. – teak Sep 20 '16 at 15:53
1

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

Roland Weisleder
  • 9,668
  • 7
  • 37
  • 59