junit

JUnit Hamcrest Example

In this example we shall show users the usage of Hamcrest. Through JUnit Hamcrest Example we will show users what is hamcrest, where it is used, why it is used, when it is used and how to use it on your applications. If you are a regular user of my JUnit series then you are already familiar with the JUnit.

If you want to see more example of JUnit, please visit my series page.

We will start by getting a little bit information about the hamcrest. It has a very good integration with JUnit and both provides a good framework for testing.

1. Introduction

Hamcrest is a open source framework matcher library used in various language to match expression for your test cases. You can visit github page if you want to explore the code of it.
Hamcrest has a very rich library of methods to fulfill our needs. It is used with different testing frameworks like JUnit and jMock.

 
Hamcrest is typically viewed as a third generation matcher framework.

  • First Generation: It typically uses assert(some statement). In this case tests are not easily readable.
  • Second Generation: It uses the special methods such as assertEquals() for test. But this approach creates a lots of assert methods.
  • Third Generation: It uses assertThat() method for test. It is more flexible and covers most of the scenarios. The benefit is that you still get fluent error messages when the assertion fails, but now you have greater extensibility.

In our example we will use assertThat() for all our tests.

2. Technologies Used

  • Java
  • JUnit 4.12 – Testing framework
  • Hamcrest 1.3 – Used for matchers
  • Eclipse – IDE for code
  • Maven – dependency management tool

3. Project SetUp

Tip
You may skip project creation and jump directly to the beginning of the example below.

Open Eclipse. Select File -> New -> Maven Project. Fill in the following details.

JUnit Hamcrest Example Setup 1
Figure 1: JUnit Hamcrest Example Setup 1

After clicking Next button, you will be taken to following screen. Simply fill out all the necessary details and click on Finish button.

JUnit Hamcrest Example Setup 2
Figure 2: JUnit Hamcrest Example Setup 2


This will create an empty maven project.

4. JUnit Hamcrest Example

Start by writing following lines to the pom.xml
pom.xml

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.hamcrest/hamcrest-library -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
        </dependency>
    </dependencies>

If you simply write JUnit in pom.xml, it will fetch hamcrest-core jar with it. But we have also included hamcrest-library jar as we need to use different matchers that are not provided by default by JUnit.

We will discuss details about each and every part of the example. First of all, let’s create a model class. This is a simple class that will help us to run our test cases.

Employee.java

package junithamcrest;

import java.util.List;

public class Employee {

	private Long empId;
	private String empName;
	private String gender;
	private List awards;

	public Employee(Long empId, String empName, String gender, List awards) {
		super();
		this.empId = empId;
		this.empName = empName;
		this.gender = gender;
		this.awards = awards;
	}

	public Long getEmpId() {
		return empId;
	}

	public void setEmpId(Long empId) {
		this.empId = empId;
	}

	public String getEmpName() {
		return empName;
	}

	public void setEmpName(String empName) {
		this.empName = empName;
	}

	public String getGender() {
		return gender;
	}

	public void setGender(String gender) {
		this.gender = gender;
	}

	public List getAwards() {
		return awards;
	}

	public void setAwards(List awards) {
		this.awards = awards;
	}
}

Now create a test class, so that we can test above class. This class will test all hamcrest matchers. We have tried to cover most common but users are advised to see other matchers if they want to dig more deeper.

JUnitHamcrestTestClass.java

package junithamcrest;

import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.everyItem;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalToIgnoringCase;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.isA;
import static org.hamcrest.Matchers.isIn;
import static org.hamcrest.Matchers.notNullValue;
import static org.hamcrest.Matchers.startsWith;
import static org.hamcrest.Matchers.stringContainsInOrder;
import static org.hamcrest.Matchers.emptyCollectionOf;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;

public class JUnitHamcrestTestClass {

	// Creating instances
	private static Employee empA;
	private static Employee empB;
	private static List strList = Arrays.asList("Apple", "Apricot", "August");

	@BeforeClass
	public static void init() {

		// creating objects 
		empA = new Employee(1001L, "Vinod Kumar Kashyap", "Male", Arrays.asList("Best Team", "Star Employee"));
		empB = new Employee(1002L, "Asmi Kashyap", "Female", Arrays.asList("Star Employee"));
	}

	/**
	 * This method will test functionality of is matcher.
	 */
	@Test
	public void isTest() {
		// checks that empA is an object of Employee class
		assertThat(empA, isA(Employee.class));

		// below are 3 versions of "is" method. All are same
		assertThat(2, equalTo(2));
		assertThat(2, is(equalTo(2)));
		assertThat(2, is(2));
	}

	/**
	 * This method will test functionality of beans matcher.
	 */
	@Test
	public void beansTest() {
		// checks that object contains the property
		assertThat(empA, hasProperty("empName"));

		// checks that the object contains the property with a value
		assertThat(empA, hasProperty("empName", equalTo("Vinod Kumar Kashyap")));
	}

	/**
	 * This method will test functionality of collections matcher.
	 */
	@Test
	public void collectionsTest() {
		// checks that object is of checked size
		assertThat(empA.getAwards(), hasSize(2));

		// checks a collection for the element present
		assertThat("Best Team", isIn(empA.getAwards()));

		// checks for empty collection
		assertThat(new ArrayList(), emptyCollectionOf(String.class));
	}

	/**
	 * This method will test functionality of String matcher.
	 */
	@Test
	public void stringTest() {
		assertThat(empA.getEmpName(), containsString("Kumar"));
		assertThat(empA.getEmpName(), endsWith("Kashyap"));
		assertThat(empB.getEmpName(), startsWith("Asmi"));

		// checks by ignoring case
		assertThat(empA.getEmpName(), equalToIgnoringCase("vinod KUMAR Kashyap"));

		// checks that the elements are occurring in the same order
		assertThat(empA.getEmpName(), stringContainsInOrder(Arrays.asList("Vinod", "Kashyap")));
	}

	/**
	 * Other common matchers
	 */
	@Test
	public void otherCommonTest() {
		// all of the conditions should be met to pass the case
		assertThat(empB.getGender(), allOf(startsWith("F"), containsString("ale")));

		// any of the conditions should be met to pass the case
		assertThat(empB.getEmpName(), anyOf(startsWith("Dhwani"), endsWith("yap")));

		// checks that value is not null
		assertThat(empA, is(notNullValue()));

		// checks that object id instance of a Class
		assertThat(empA.getEmpId(), instanceOf(Long.class));

		// checks every item in  list
		assertThat(strList, everyItem(startsWith("A")));
	}
}

Now we will start with explanation part by part of the example. Most of the matchers are self explanatory.

4.1 Is Matcher

This is one of the most common matcher used.

	@Test
	public void isTest() {
		// checks that empA is an object of Employee class
		assertThat(empA, isA(Employee.class));

		// below are 3 versions of "is" method. All are same
		assertThat(2, equalTo(2));
		assertThat(2, is(equalTo(2)));
		assertThat(2, is(2));
	}

Line no 7,8,9 works exactly same. The last form is allowed since is(T value) is overloaded to return is(equalTo(value)).

4.2 Beans Matchers

These matchers are used to check out beans.

	@Test
	public void beansTest() {
		// checks that object contains the property
		assertThat(empA, hasProperty("empName"));

		// checks that the object contains the property with a value
		assertThat(empA, hasProperty("empName", equalTo("Vinod Kumar Kashyap")));
	}

If you see here, we are testing that our class has a property associated with it or not.

4.3 Collections Matchers

These matchers works with the collections. JUnit and Hamcrest provides various ways to test collections.

	@Test
	public void collectionsTest() {
		// checks that object is of checked size
		assertThat(empA.getAwards(), hasSize(2));

		// checks a collection for the element present
		assertThat("Best Team", isIn(empA.getAwards()));

		// checks for empty collection
		assertThat(new ArrayList(), emptyCollectionOf(String.class));
	}

4.4 String Matchers

These matchers helps to work with Strings.

	@Test
	public void stringTest() {
		assertThat(empA.getEmpName(), containsString("Kumar"));
		assertThat(empA.getEmpName(), endsWith("Kashyap"));
		assertThat(empB.getEmpName(), startsWith("Asmi"));

		// checks by ignoring case
		assertThat(empA.getEmpName(), equalToIgnoringCase("vinod KUMAR Kashyap"));

		// checks that the elements are occurring in the same order
		assertThat(empA.getEmpName(), stringContainsInOrder(Arrays.asList("Vinod", "Kashyap")));
	}

4.5 Other Common Matchers

There are many different matchers used. Here we are using some of the common matchers. It is also possible to chain matchers, via the anyOf() of allOf() method. See below for details.

	@Test
	public void otherCommonTest() {
		// all of the conditions should be met to pass the case
		assertThat(empB.getGender(), allOf(startsWith("F"), containsString("ale")));

		// any of the conditions should be met to pass the case
		assertThat(empB.getEmpName(), anyOf(startsWith("Dhwani"), endsWith("yap")));

		// checks that value is not null
		assertThat(empA, is(notNullValue()));

		// checks that object id instance of a Class
		assertThat(empA.getEmpId(), instanceOf(Long.class));

		// checks every item in  list
		assertThat(strList, everyItem(startsWith("A")));
	}

Line no 4 uses allOf() matcher. It defines that all of the condition inside should match to pass the test.
Line no 7 uses anyOf() matcher, which tells us that if any of the condition is matched, test case will pass. As you see that in our scenario first condition is not matched but second one does. This case passes with flying colors. Because any one of the conditions is true.
Line no 16 scans every item in a list and matches the condition. If condition is matched it will pass the test.

5. Output

For running the example simply right click on class and Run As -> Junit Test. You will see the following output in JUnit console.

JUnit Hamcrest Example Output
Figure 3: JUnit Hamcrest Example Output

5. Conclusion

JUnit Hamcrest Example focus mostly on the usage of the JUnit Hamcrest matchers. You have learned what is hamcrest, why we should use it, where it should be used, how to use it. This example shows the usage of a simple example which covers most if the matchers.

6. Download the Eclipse project

This is JUnit Hamcrest Example.

Download
You can download the full source code of this example here: JUnitHamcrest.zip

Vinod Kumar Kashyap

Vinod is Sun Certified and love to work in Java and related technologies. Having more than 13 years of experience, he had developed software's including technologies like Java, Hibernate, Struts, Spring, HTML 5, jQuery, CSS, Web Services, MongoDB, AngularJS, AWS. He is also a JUG Leader of Chandigarh Java User Group.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button