jck28-桔子-junit5之Hamcrest断言

  • 常用断言

    • is
    • equalTo
    • not
    • hasItem
    • allOf
    • anyOf
    • both
    • either
  • is(T)

    • 将一个对象作为参数来检查相等性
  • is(Matcher<T>)

    • 使用另一个匹配器,使相等性语句更具表现力
@Test
void UsingIsForMatch(){
    String testString = "hamcrest core Is match";
    assertThat(testString, is("hamcrest core Is match"));
    assertThat(testString, is(equalTo("hamcrest core Is match")));
}
  • 检查给定对象的不相等性
  • not(T)
    • 接受一个对象作为参数
  • not(Matcher<T>)
    • 接受另一个匹配器
@Test
void UsingNotForMatch(){
    String testString = "hamcrest not match";
    assertThat(testString, not("hamcrest other match"));
    assertThat(testString, is(not(equalTo("hamcrest other match"))));
    assertThat(testString, is(not(instanceOf(Integer.class))));

}
  • hasItem(T)
  • hasItem(Matcher<? extends T>)
  • 检查的 Iterable 集合是否与给定对象或匹配器匹配
  • 也可以对多个项目进行断言
@Test
void UsingHasItemForMatch(){
    List<String> list = Arrays.asList("java", "hamcrest", "JUnit5");

    assertThat(list, hasItem("java"));
    assertThat(list, hasItem(isA(String.class)));

    assertThat(list, hasItems("java", "JUnit5"));
    assertThat(list, hasItems(isA(String.class), endsWith("est")));
}
  • allOf(Matcher<? extends T>…)
  • 断言实际对象是否与所有指定条件匹配,全部匹配才会pass
@Test
void UsingAllOfForMatch(){
    String testString = "Achilles is powerful";
    assertThat(testString, allOf(
      startsWith("Achi"), endsWith("ul"), containsString("Achilles")));

}
  • anyOf(Matcher<? extends T>…)
  • 检查的对象匹配任何指定的条件,则匹配{style=width:500px}
@Test
void UsingAllOfForMatch(){
    String testString2 = "Hector killed Achilles";
    assertThat(testString2, anyOf(startsWith("Hec"), containsString("baeldung")));
}
  • both(Matcher<? extends T>)
    • and 配合使用{style=width:500px}
  • 两个指定条件都匹配检查对象时匹配{style=width:500px}
@Test
void UsingBothForMatch(){
    String testString = "daenerys targaryen";
    assertThat(testString, both(startsWith("daene")).and(containsString("yen")));

}
  • either(Matcher<? extends T>)
    • or 配合使用{style=width:500px}
  • 任一指定条件与检查对象匹配时匹配{style=width:500px}
@Test
void UsingBothForMatch(){
    String testString = "daenerys targaryen";
    assertThat(testString, both(startsWith("daene")).and(containsString("yen")));
    assertThat(testString, either(startsWith("tar")).or(containsString("targaryen")));

}