Here we going to figure out few tips how to make your test failures more informative, clear and valuable with AssertJ custome messages.
AssertJ Maven dependency
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<!-- use 2.9.0 for Java 7 projects -->
<version>3.9.0</version>
<scope>test</scope>
</dependency>
Check the current available version - AssertJ
By default AssertJ assertion failures
int multiplicand1 = 2
int multiplicand2 = 3
int expectedResult = 5;
assertions.assertThat(multiplicand1 * multiplicand2)
.isEqualTo(expectedResult);
give fail mesagges like this:
1) expected:<[5]> but was:<[6]>
We can’t see what exactly the failure is about.
Let’s tune it a little with as(...)
method
...
assertions.assertThat(multiplicand1 * multiplicand2)
.as("2 * 3")
.isEqualTo(expectedResult);
...
Failure output:
1) [2 * 3] expected:<[5]> but was:<[6]>
or even
...
assertions.assertThat(multiplicand1 * multiplicand2)
.as("Multiplication %s * %s", multiplicand1, multiplicand2)
.isEqualTo(expectedResult);
...
Failure output:
1) [Multiplication 2 * 3] expected:<[5]> but was:<[6]>
Better?
We also can completely replace the failure message with our custome message using withFailMessage(...)
:
...
assertions.assertThat(multiplicand1 * multiplicand2)
.withFailMessage("Multiplication error <%s * %s> should be equal <%s> but was <%s>",
multiplicand1, multiplicand2, expectedResult, multiplicand1 * multiplicand2)
.isEqualTo(expectedResult);
...
Failure output:
1) Multiplication error <2 * 3> should be equal <5> but was <6>
And the last thing - don’t forget to give clear and informative names to test classes and test methods.
You may also find these posts interesting: