How to assert that a list has at least n items which are greater than x (with hamcrest in junit)

后端 未结 2 1280
情歌与酒
情歌与酒 2020-12-06 21:33

I could with following code check if a list has a item, which greater than 30.

//Using Hamcrest
List ints= Arrays.asList(22,33,44,55);
assertT         


        
相关标签:
2条回答
  • 2020-12-06 22:08

    Another simple way to test it is

    assertTrue(ints.size() >= 3);
    
    0 讨论(0)
  • 2020-12-06 22:12

    You can create your own specific matcher, like:

    class ListMatcher {
      public static Matcher<List<Integer>> hasAtLeastItemsGreaterThan(final int targetCount, final int lowerLimit) {
        return new TypeSafeMatcher<List<Integer>>() {
    
            @Override
            public void describeTo(final Description description) {
                description.appendText("should have at least " + targetCount + " items greater than " + lowerLimit);
            }
    
            @Override
            public void describeMismatchSafely(final List<Integer> arg0, final Description mismatchDescription) {
                mismatchDescription.appendText("was ").appendValue(arg0.toString());
            }
    
            @Override
            protected boolean matchesSafely(List<Integer> values) {
                int actualCount = 0;
                for (int value : values) {
                    if (value > lowerLimit) {
                        actualCount++;
                    }
    
                }
                return actualCount >= targetCount;
            }
        };
    }
    }
    

    And then use it like:

    public class ListMatcherTests {
    
    @Test
    public void testListMatcherPasses() {
        List<Integer> underTest = Arrays.asList(1, 10, 20);
        assertThat(underTest, ListMatcher.hasAtLeastItemsGreaterThan(2, 5));
    }
    
    @Test
    public void testListMatcherFails() {
        List<Integer> underTest = Arrays.asList(1, 10, 20);
        assertThat(underTest, ListMatcher.hasAtLeastItemsGreaterThan(2, 15));
    }
    

    Of course, this is a bit of work; and not very generic. But it works.

    Alternatively, you could simply "iterate" your list within your specific test method.

    0 讨论(0)
提交回复
热议问题