Overview
Hamcrest is a framework that allows you to use its matchers to check for different conditions. These matchers happen to be very useful in doing unit tests. Besides, Hamcrest has the goal to make its matchers as readable as possible. For examples,
assertThat(actual, is(equalTo(expected))); assertThat(actual, is(not(equalTo(expected)))); assertThat("test", anyOf(is("testing"), containsString("est")));
Installation
- Download the latest JAR version of Hamcrest(e.g.
hamcrest-2.1.jar
) from https://mvnrepository.com/artifact/org.hamcrest/hamcrest. - Add the JAR file to your library class path.
Here is a video showing how to add Hamcrest in Eclipse.
Examples
import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; public class UsingHamcrest { public static void main(String[] args) { String str="Xuan"; // Examples in matching context. //------------------------------- // Positive match. str="Xuan"; if( equalTo("Xuan").matches(str) ) System.out.println("The string is equal to Xuan."); else System.out.println("The string is NOT equal to Xuan."); // Negative match. str = "Some very long string."; if( containsString("Xuan").matches(str) ) System.out.println("String does contain 'Xuan'."); else System.out.println("String does NOT contain 'Xuan'."); // Examples in unit test context. //------------------------------- // Exception thrown. str = "Assert string containing something."; assertThat(str, is(equalTo("Not found"))); } }
Output
Github
- https://github.com/xuanngo2001/java-hamcrest
Reference
- List of all matchers that you can use:
allOf()
,any()
,anyOf()
,anything()
,both()
,containsString()
,describedAs()
,either()
,endsWith()
,equalTo()
,everyItem()
,hasItems()
,instanceOf()
,is()
,isA()
,not()
,notNullValue()
,nullValue()
,sameInstance()
,startsWith()
,theInstance()
, etc.