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

♀尐吖头ヾ 提交于 2019-11-26 23:33:07

问题


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

//Using Hamcrest
List<Integer> ints= Arrays.asList(22,33,44,55);
assertThat(ints,hasItem(greaterThan(30)));

But how could I assert if a list has at least 2 items, which are greater than 30?

With AssertJ, there is a solution I know. But I have no idea how to realize that with Hamcrest.

//Using AssertJ
List<Integer> ints= Arrays.asList(22,33,44,55);
Condition<Integer> greaterThanCondition = new Condition<Integer>("greater") {
        @Override
        public boolean matches (Integer i){
            return i>30;
        }
    } ;
assertThat(ints).haveatLeast(2,greaterThanCondition);

回答1:


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.




回答2:


Another simple way to test it is

assertTrue(ints.size() >= 3);


来源:https://stackoverflow.com/questions/39156069/how-to-assert-that-a-list-has-at-least-n-items-which-are-greater-than-x-with-ha

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!