java – 如何断言列表至少有n个大于x的项(在junit中使用hamcrest)

我可以使用以下代码检查列表是否有一个大于30的项目.

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

但是,如果列表中至少有2个项目大于30,我怎么断言呢?

有了AssertJ,我知道有一个解决方案.但我不知道如何用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);

解决方法:

您可以创建自己的特定匹配器,例如:

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;
        }
    };
}
}

然后使用它像:

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));
}

当然,这是一项工作;并不是很通用.但它的确有效.

或者,您可以在特定的测试方法中简单地“迭代”您的列表.

上一篇:JUnit注解


下一篇:java-Hamcrest中的stringContainsInAnyOrder匹配项?