【问题标题】:How to assert that a list has at least n items which are greater than x (with hamcrest in junit)如何断言一个列表至少有 n 个大于 x 的项目(在 junit 中使用 hamcrest)
【发布时间】:2016-08-25 23:09:00
【问题描述】:

我可以使用以下代码检查列表是否有大于 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);

【问题讨论】:

    标签: java junit hamcrest


    【解决方案1】:

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

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

    当然,这有点工作;而且不是很通用。但它有效。

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

    【讨论】:

      【解决方案2】:

      另一种简单的测试方法是

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

      【讨论】:

      • 问题不是关于集合的大小,而是关于大于某个 X 的整数集合中的项目数。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多