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

JUnit:assert集合包含具有特定属性的元素

  •  0
  • dhalfageme  · 技术社区  · 4 年前

    如果集合包含具有特定属性值的元素,我想断言(使用JUnit而不是像hamcrest这样的任何其他依赖项)。

    我发现了这个问题 How do I assert an Iterable contains elements with a certain property? 使用harmcrest。

    一种方法是重写Equals方法,只检查要比较的属性,但这不是一个好的解决方案。

    有没有一种使用JUnit4实现这一点的优雅方法,或者我应该编写它并遍历集合来检查值?

    谢谢

    1 回复  |  直到 4 年前
        1
  •  0
  •   Mureinik    4 年前

    Java 8的流和过滤实际上非常优雅:

    Collection<SomeObejct> myCollection = /* something */;
    boolean hasAny = myCollection.stream().anyMatch(s -> s.getProperty().equals("something"));
    assertTrue("Couldn't find an object with the right property", hasAny);