How to use JUnit and Hamcrest together? How to use JUnit and Hamcrest together? java java

How to use JUnit and Hamcrest together?


If you're using a Hamcrest with a version greater or equal than 1.2, then you should use the junit-dep.jar. This jar has no Hamcrest classes and therefore you avoid classloading problems.

Since JUnit 4.11 the junit.jar itself has no Hamcrest classes. There is no need for junit-dep.jar anymore.


junit provides new check assert methods named assertThat() which uses Matchers and should provide a more readable testcode and better failure messages.

To use this there are some core matchers included in junit. You can start with these for basic tests.

If you want to use more matchers you can write them by yourself or use the hamcrest lib.

The following example demonstrates how to use the empty matcher on an ArrayList:

package com.test;import static org.hamcrest.Matchers.empty;import static org.hamcrest.Matchers.is;import static org.junit.Assert.assertThat;import java.util.ArrayList;import java.util.List;import org.junit.Test;public class EmptyTest {    @Test    public void testIsEmpty() {        List myList = new ArrayList();        assertThat(myList, is(empty()));    }}

(I included the hamcrest-all.jar in my buildpath)


Not exactly answering your question, but you should definitely try FEST-Assert fluent assertions API. It's competing with Hamcrest, but has a much easier API with only one static import required. Here is the code provided by cpater using FEST:

package com.test;import java.util.ArrayList;import java.util.List;import org.junit.Test;import static org.fest.assertions.Assertions.assertThat;public class EmptyTest {    @Test    public void testIsEmpty() {        List myList = new ArrayList();        assertThat(myList).isEmpty();    }  }

EDIT: Maven coordinates:

<dependency>  <groupId>org.easytesting</groupId>  <artifactId>fest-assert</artifactId>  <version>1.4</version>  <scope>test</scope></dependency>