有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么我应该使用HamcrestMatcher和assertThat()而不是传统的assertXXX()方法

当我看到断言类JavaDoc中的示例时

assertThat("Help! Integers don't work", 0, is(1)); // fails:
// failure message:
// Help! Integers don't work
// expected: is <1> 
// got value: <0>
assertThat("Zero is one", 0, is(not(1))) // passes

我看不出比……比如说,assertEquals( 0, 1 )有什么大的优势

如果构造变得更复杂,那么消息可能会更好,但是你看到了更多的优势吗?可读性


共 (2) 个答案

  1. # 1 楼答案

    基本上是为了提高代码的可读性

    除了hamcrest,您还可以使用fest assertions。 与hamcrest相比,他们有一些优势,例如:

    • 它们更具可读性
      assertEquals(123, actual); // reads "assert equals 123 is actual"vs
      assertThat(actual).isEqualTo(123); // reads "assert that actual is equal to 123")
    • 它们是可发现的(you can make autocompletion work with any IDE

    一些例子

    import static org.fest.assertions.api.Assertions.*;
    
    // common assertions
    assertThat(yoda).isInstanceOf(Jedi.class);
    assertThat(frodo.getName()).isEqualTo("Frodo");
    assertThat(frodo).isNotEqualTo(sauron);
    assertThat(frodo).isIn(fellowshipOfTheRing);
    assertThat(sauron).isNotIn(fellowshipOfTheRing);
    
    // String specific assertions
    assertThat(frodo.getName()).startsWith("Fro").endsWith("do")
                               .isEqualToIgnoringCase("frodo");
    
    // collection specific assertions
    assertThat(fellowshipOfTheRing).hasSize(9)
                                   .contains(frodo, sam)
                                   .excludes(sauron);
    
    
    // map specific assertions (One ring and elves ring bearers initialized before)
    assertThat(ringBearers).hasSize(4)
                           .includes(entry(Ring.oneRing, frodo), entry(Ring.nenya, galadriel))
                           .excludes(entry(Ring.oneRing, aragorn));
    

    2016年10月17日更新

    Fest不再处于活动状态,请改用AssertJ

  2. # 2 楼答案

    对于那些存在完全符合您意图的assertFoo的情况,没有什么大的优势。在这些情况下,它们的行为几乎相同

    但当你面对更复杂的检查时,优势就变得更加明显:

    val foo = List.of("someValue");
    assertTrue(foo.contains("someValue") && foo.contains("anotherValue"));
    
    Expected: is <true>
             but: was <false>
    

    val foo = List.of("someValue");
    assertThat(foo, containsInAnyOrder("someValue", "anotherValue"));
    
    Expected: iterable with items ["someValue", "anotherValue"] in any order
         but: no item matches: "anotherValue" in ["someValue"]
    

    我们可以讨论其中哪一个更容易阅读,但一旦断言失败,您将从assertThat得到一条很好的错误消息,但从assertTrue得到的信息量非常少