如何断言一个列表至少有 n 个大于 x 的项目(在 junit 中有 hamcrest) [英] How to assert that a list has at least n items which are greater than x (with hamcrest in junit)

查看:16
本文介绍了如何断言一个列表至少有 n 个大于 x 的项目(在 junit 中有 hamcrest)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

但是我如何断言列表是否至少有 2 个大于 30 的项目?

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

使用 AssertJ,我知道有一个解决方案.但我不知道如何使用 Hamcrest 来实现这一点.

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

推荐答案

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

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

然后像这样使用它:

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.

这篇关于如何断言一个列表至少有 n 个大于 x 的项目(在 junit 中有 hamcrest)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆