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

使用Hamcrest(Java 8)检查特定的映射值属性(谓词)

  •  0
  • gavenkoa  · 技术社区  · 6 年前

    Consumer :

    @AllArgsConstructor
    @Getter
    public static class User {
        private Long id;
        private String name;
    }
    
    @Test
    public void x() {
        Map<String, User> map = new HashMap<>();
        map.put("key", new User(123, "Random Hacker"));
        Assertions.assertThat(map).hasEntrySatisfying("key", __ -> {
            Assertions.assertThat(__.getName()).isEqualTo("Random Hacker");
        });
    }
    

    Map 具有Hamcrest的给定键的值(以及键/值的存在)?

    笔记 public SELF hasEntrySatisfying(K key, Consumer<? super V> valueRequirements) 已从v3.6.0(2016-11-21)起添加到AspectJ中。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Michael Wiles    6 年前

    Using Hamcrest for testing - Tutorial

    其用法如下所示 such :

    org.hamcrest.MatcherAssert.assertThat(myMap, org.hamcrest.Matchers.hasEntry("bar", "foo"))
    

    如果你需要一个更通用的匹配器,有 this 方法:

    例子:

    assertThat(myMap, hasEntry(equalTo("bar"), equalTo("foo")))