Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
327 views
in Technique[技术] by (71.8m points)

java - What is the idiomatic Hamcrest pattern to assert that each element of an iterable matches a given matcher?

Examine the following snippet:

    assertThat(
        Arrays.asList("1x", "2x", "3x", "4z"),
        not(hasItem(not(endsWith("x"))))
    );

This asserts that the list doesn't have an element that doesn't end with "x". This, of course, is the double negatives way of saying that all elements of the list ends with "x".

Also note that the snippet throws:

java.lang.AssertionError: 
Expected: not a collection containing not a string ending with "x"
     got: <[1x, 2x, 3x, 4z]>

This lists the entire list, instead of just the element that doesn't end with "x".

So is there an idiomatic way of:

  • Asserting that each element ends with "x" (without double negatives)
  • On assertion error, list only those elements that doesn't end with "x"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are looking for everyItem():

assertThat(
    Arrays.asList("1x", "2x", "3x", "4z"),
    everyItem(endsWith("x"))
);

This produces a nice failure message:

Expected: every item is a string ending with "x"
     but: an item was "4z"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...