代码之家  ›  专栏  ›  技术社区  ›  ewok

Junit:断言一个列表至少包含一个与某个条件匹配的属性

  •  2
  • ewok  · 技术社区  · 6 年前

    我有一个方法可以返回类型为 MyClass . 类名 有很多属性,但我关心 type count "Foo" 数一数 1

    我试图找出如何做到这一点,而不必在返回的列表上循环,并逐个检查每个元素,如果发现一个元素通过,就会中断,例如:

        boolean passes = false;
        for (MyClass obj:objects){
            if (obj.getName() == "Foo" && obj.getCount() == 1){
                passes = true;
            }
        }
        assertTrue(passes);
    

    我真的不喜欢这种结构。我想知道有没有更好的方法 assertThat 还有一些火柴。

    3 回复  |  直到 6 年前
        1
  •  3
  •   logee    6 年前

    汉克雷斯特进口

    import static org.hamcrest.Matchers.allOf;
    import static org.hamcrest.Matchers.hasItem;
    import static org.hamcrest.Matchers.hasProperty;
    import static org.hamcrest.Matchers.is;
    import static org.junit.Assert.assertThat;
    

    你可以用

        assertThat(foos, hasItem(allOf(
            hasProperty("name", is("foo")),
            hasProperty("count", is(1))
        )));
    
        2
  •  1
  •   Tom Hawtin - tackline    6 年前
    assertTrue(objects.stream().anyMatch(obj ->
        obj.getName() == "Foo" && obj.getCount() == 1
    ));
    

    或者更可能:

    assertTrue(objects.stream().anyMatch(obj ->
        obj.getName().equals("Foo") && obj.getCount() == 1
    ));
    
        3
  •  1
  •   Charles    6 年前

    public class TestClass {
        String name;
        int count;
    
        public TestClass(String name, int count) {
            this.name = name;
            this.count = count;
        }
    
        public String getName() {
            return name;
        }
    
        public int getCount() {
            return count;
        }
    }
    
    @org.junit.Test
    public void testApp() {
        List<TestClass> moo = new ArrayList<>();
        moo.add(new TestClass("test", 1));
        moo.add(new TestClass("test2", 2));
    
        MatcherAssert.assertThat(moo,
                Matchers.hasItem(Matchers.both(Matchers.<TestClass>hasProperty("name", Matchers.is("test")))
                        .and(Matchers.<TestClass>hasProperty("count", Matchers.is(1)))));
    }