Truth makes your test assertions and failure messages more readable. Similar to AssertJ, it natively supports many JDK and Guava types, and it is extensible to others.
- IDE auto complete, faster to type
- actual is always on the left-hand side, the expected value is always on the right-hand side.
- So readers knows what we are testing.
- Detailed, meaningful, and easy-to-read error messages
- Hamcrest doesn’t autocomplete statements in IDEs.
- containsExactlyElementsIn
- Use
containsExactly
insteadof isEqualTo(ImmutableMap.of(k1,v1,k2,v2))
- containsExactly, containsAtLeast, etc are order-independent assertions; chain .inOrder() to check the order.
- Use
assertWithMessage
to customize error message. - Writing your own custom subject
- Truth8 for java8 types such as java.util.Optional
- ProtoTruth for Message style protocol buffers and lite versions
- Re2jSubjects for use with the RE2J library
Test Exception
- Don’t use
@Rule ExpectedException
- Any statements after the throwing call will never be executed.
- Don’t use
@Test(expected = ExceptionExpectation.class)
- The test passes if any statement throws ExceptionExpectation.
- If the method should throw FooException, test for FooException, not generic RuntimeException or its parent class.
- perform additional assertions on the exception: hasMessageThat etc if appropriate.
- Use
Throwables.getCauseAs
instead of (MyExpectedCause) ex.getCause()
Throwables.getCauseAs
includes the original exception in the failure if the cause is not of the expected type
Resource