How to use Hamrest for unit test assertions
Hamrest is a framework for writing unit test assertions. It provides a set of methods that can be used to compare and validate relationships between objects, making it easier to read and test assertions for expressions.
The commonly used Hamrest key methods include:
1. EqualTo(): Used to compare whether two objects are equal.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
assertThat(actualValue, equalTo(expectedValue));
2. is(): Used to determine whether the object meets specific conditions.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
assertThat(actualValue, is(expectedValue));
3. not(): Used to determine whether the object does not meet specific conditions.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.not;
assertThat(actualValue, not(expectedValue));
4. containsString(): Used to determine whether a string contains a specified substring.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
assertThat(actualString, containsString(expectedSubstring));
In order to use Hamrest, the following dependencies need to be added to the pom.xml file in the Maven project:
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-all</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
This will add the Hamrest framework and all Matcher classes to the project for writing unit test assertions. Then, you can use the above example code to write more readable and expressive assertions.