Hamcrest Matchers: Software Testing Cheat Sheet
Published on: August 30, 2024
Writing JUnit assertions is over! It's time to use Hamcrest assertions for more readable and flexible tests.
Hamcrest Matchers is a Java library that provides a flexible and readable way to write assertions, making it easier to match arrays, collections, numbers, strings, and other objects in tests. It is commonly used for unit testing and works well with JUnit, TestNG, and other testing frameworks. Hamcrest is not bundled by default with JUnit 5 but is included in JUnit 4. In Maven projects, if using JUnit 4, Hamcrest is already available. However, for JUnit 5 or standalone usage, you must explicitly add the Hamcrest dependency in your pom.xml.
Below are a few commonly used Hamcrest assertions:
Assertion | Matcher | Description |
---|---|---|
assertThat(value, equalTo(expected)) | equalTo() | Checks if the value is equal to the expected value. |
assertThat(value, not(equalTo(expected))) | not() | Checks if the value is **not** equal to the expected value. |
assertThat(value, greaterThan(expected)) | greaterThan() | Checks if the value is greater than the expected value. |
assertThat(value, lessThan(expected)) | lessThan() | Checks if the value is less than the expected value. |
assertThat(value, containsString(expected)) | containsString() | Checks if the string contains the expected substring. |
assertThat(value, startsWith(expected)) | startsWith() | Checks if the string starts with the expected prefix. |
assertThat(value, endsWith(expected)) | endsWith() | Checks if the string ends with the expected suffix. |
assertThat(value, hasSize(expected)) | hasSize() | Checks if the collection has the expected size. |
assertThat(value, hasItem(expected)) | hasItem() | Checks if the collection contains the expected item. |
assertThat(value, empty()) | empty() | Checks if the collection is empty. |
Hamcrest’s expressive matchers make your unit tests more readable and maintainable. They allow for complex assertions in a simple, fluent style and can be extended to suit the needs of your project. Whether you're working on simple tests or more complex integrations, Hamcrest provides powerful tools for verifying your code.
Check a sample test using Hamcrest Matcher assertion here: Hamcrest Test Example