Can you add a custom message to AssertJ assertThat?

前端 未结 4 1552
北海茫月
北海茫月 2020-12-24 04:17

We have a test suite that primarily uses JUnit assertions with Hamcrest matchers. One of our team started experimenting with AssertJ and impressed people with its syntax, fl

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 04:53

    To add another option to Patrick M's answer:

    Instead of using Descriptable.as, you can also use AbstractAssert.withFailMessage():

    try {
      // set a bad age to Mr Frodo which is really 33 years old.
      frodo.setAge(50);
      // you can specify a test description via withFailMessage(), supports String format args
      assertThat(frodo.getAge()).
        withFailMessage("Frodo's age is wrong: %s years, difference %s years",
          frodo.getAge(), frodo.getAge()-33).
        isEqualTo(33);
    } catch (AssertionError e) {
      assertThat(e).hasMessage("Frodo's age is wrong: 50 years, difference 17 years");
    }
    

    The difference to using Descriptable.as is that it gives you complete control over the custom message - there is no "expected" and "but was".

    This is useful where the actual values being tested are not useful for presentation - this method allows you to show other, possibly calculated values instead, or none at all.


    Do note that, just like Descriptable.as, you must call withFailMessage() before any actual assertions - otherwise it will not work, as the assertion will fire first. This is noted in the Javadoc.

提交回复
热议问题