By Chris Povirk, Java Core Libraries

Software testing is important—and sometimes frustrating. The frustration can come from working on innately hard domains, like concurrency, but too often it comes from a thousand small cuts:

assertEquals("Message has been sent", getString(notification, EXTRA_BIG_TEXT));
assertTrue(
getString(notification, EXTRA_TEXT)
.contains("Kurt Kluever "));

The two assertions above test almost the same thing, but they are structured differently. The difference in structure makes it hard to identify the difference in what’s being tested.

A better way to structure these assertions is to use a fluent API:
assertThat(getString(notification, EXTRA_BIG_TEXT))
.isEqualTo("Message has been sent");
assertThat(getString(notification, EXTRA_TEXT))
.contains("Kurt Kluever ");

A fluent API naturally leads to other advantages:

  • IDE autocompletion can suggest assertions that fit the value under test, including rich operations like containsExactly(permission.SEND_SMS, permission.READ_SMS).
  • Failure messages can include the value under test and the expected result. Contrast this with the assertTrue call above, which lacks a failure message entirely.
Google’s fluent assertion library for Java and Android is Truth. We’re happy to announce that we’ve released Truth 1.0, which stabilizes our API after years of fine-tuning.

Truth started in 2011 as a Googler’s personal open source project. Later, it was donated back to Google and cultivated by the Java Core Libraries team, the people who bring you Guava.

You might already be familiar with assertion libraries like Hamcrest and AssertJ, which provide similar features. We’ve designed Truth to have a simpler API and more readable failure messages. For example, here’s a failure message from AssertJ:
java.lang.AssertionError:
Expecting:
<[year: 2019
month: 7
day: 15
]>
to contain exactly in any order:
<[year: 2019
month: 6
day: 30
]>
elements not found:
<[year: 2019
month: 6
day: 30
]>
and elements not expected:
<[year: 2019
month: 7
day: 15
]>

And here’s the equivalent message from Truth:

value of:
iterable.onlyElement()
expected:
year: 2019
month: 6
day: 30

but was:
year: 2019
month: 7
day: 15
For more details, read our comparison of the libraries, and try Truth for yourself.
Also, if you’re developing for Android, try AndroidX Test. It includes Truth extensions that make assertions even easier to write and failure messages even clearer:
assertThat(notification).extras().string(EXTRA_BIG_TEXT)
.isEqualTo("Message has been sent");
assertThat(notification).extras().string(EXTRA_TEXT)
.contains("Kurt Kluever ");
Coming soon: Kotlin users of Truth can look forward to Kotlin-specific enhancements.