Truth: Fluent Assertions for Clearer Tests
Truth makes tests read like English: `assertThat(actual).is...`. It provides clearer assertions than standard JUnit, with far more helpful failure messages, especially for collections. The main footgun is a potential Guava dependency conflict.
WHY IT EXISTS Standard test assertions like assertEquals are functional but often produce unhelpful failure messages and can be awkward to read. They put the expected value first, which obscures the context of what's being tested, forcing you to read the whole line to understand the intent.
THE MENTAL MODEL Think of Truth as a translator that turns test assertions into clear, readable sentences. Instead of comparing two disconnected values, you start with the subject (assertThat(thisThing)) and then describe what should be true about it (.contains("that")). This fluency extends to its failure messages, which explain why the assertion failed in detail, not just that it failed.
HOW IT WORKS Truth uses a fluent API with chained method calls. You start every assertion with a static import of assertThat(). The object you pass to assertThat() determines the available assertion methods your IDE can autocomplete. For example, assertThat(myList) will show collection-related assertions like containsExactly() or isEmpty(), while assertThat(myString) will show startsWith() or contains(). This type-awareness makes it discoverable and easy to use.
WHEN TO USE IT Use Truth as your default assertion library in Java and Android projects. It is especially powerful for testing collections, where its failure messages save significant debugging time. For example, when comparing two collections, Truth will tell you which elements are missing, which are extra, and which are out of order, rather than just saying the collections are not equal. It works on Android out-of-the-box.
WHEN NOT TO USE IT Truth's API is intentionally simpler than alternatives like AssertJ. If you need a highly specific or obscure assertion that Truth doesn't provide, you might need a different library. Also, if a project already uses Hamcrest matchers heavily for mocking, introducing another assertion library might add unnecessary complexity.
ONE CANONICAL EXAMPLE A standard JUnit assertion for a collection might be assertEquals(expectedSet, actualSet). If it fails, the message is just a dump of the two collections. The Truth equivalent is assertThat(actualSet).containsExactlyElementsIn(expectedSet). If this fails because an element "truth" is missing, the error message will be explicit: value of: mySet missing (1): truth --- expected: [...] but was: [...]. This immediately tells you the problem.
Read the original → truth.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.