Ticker

6/recent/ticker-posts

Ad Code

Responsive Advertisement

How to use Hamcrest assertThat() Matchers to Create JUnit testcases in Java – Complete Tutorial

How to use Hamcrest assertThat() Matchers to Create JUnit testcases in Java

How to use Hamcrest for testing? Sometime back I’ve written a Hello World JUnit Article with all details. In this tutorial we will go over steps on how to use Hamcrest to create JUnit for your Java project.

Hamcrest is a testing framework for Java with matchers bundled with the JUnit framework to create more readable Java unit tests. I tried it today and I absolutely love it.

Very simple and complete documentation makes it perfect.

If you have any of below questions then you are at right place:

  • Writing JUnit test cases in Java using Eclipse
  • How to write junit test cases in Java
  • Sample JUnit test cases in Java
  • Writing JUnit test cases using Hamcrest Matchers
  • The Benefits of assertThat vs Assert Methods in JUnit Tests
  • hamcrest assertthat() tutorial

Let’s get started:

Create Java class CrunchifyHemcrestJUnitTest.java in Eclipse. We are going to create 4 different category of tests.

  1. Create JUnit testcases for Java List
  2. Create JUnit testcases for Java Map
  3. Create JUnit testcases for Java Object
  4. Create JUnit testcases for Null Check

Here are the top Hamcrest matchers:

  • is()
  • hasItems()
  • hasSize()
  • contains()
  • containsInAnyOrder()

Below tutorial covers almost all matchers testcases which will pass all the time. Just modify to create false positive and so on.

You need to add below maven dependency in your project.

<dependency>
        <groupId>org.hamcrest</groupId>
        <artifactId>hamcrest-all</artifactId>
        <version>1.3</version>
</dependency>

Just add this to pom.xml file. If you don’t see pom.xml then follow this tutorial.

containsinanyorder-hamcrest-java-junit-test

Here is a complete Java code

Just right click on a class and Run As -> JUnit Test.

CrunchifyHamcrestJUnitTest.java

package crunchify.com.java.tutorials;

import org.hamcrest.collection.IsEmptyCollection;
import org.hamcrest.collection.IsMapContaining;
import org.hamcrest.core.IsNull;
import org.junit.Test;

import java.util.*;

import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasProperty;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;

/**
 * @author Crunchify.com
 * <p>
 * Hamcrest JUnit Tutorials by Crunchify.com
 * 1. Create JUnit testcases for Java List
 * 2. Create JUnit testcases for Java Map
 * 3. Create JUnit testcases for Java Object
 * 4. Create JUnit testcases for Null Check
 */

public class CrunchifyHamcrestJUnitTest {
        
        // Testcase-1: JUnit for List
        @Test
        public void crunchifyListJUnitTests() {
                
                // List: An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.
                // The user can access elements by their integer index (position in the list), and search for elements in the list.
                List<String> company = Arrays.asList("Crunchify.com", "Google.com", "Facebook.com");
                
                // asList(): Returns a fixed-size list backed by the specified array. Changes made to the array will be visible in the returned list,
                // and changes made to the list will be visible in the array.
                // The returned list is Serializable and implements RandomAccess.
                List<String> crunchifyCompany = Arrays.asList("Crunchify.com", "Google.com", "Facebook.com");
                
                crunchifyLog("\n~~~~~~~~~~~JUnit List Check Test~~~~~~~~~~~");
                
                crunchifyLog("1) assertThat(company, is(crunchifyCompany)) check");
                // A shortcut to the frequently used is(equalTo(x)).
                assertThat(company, is(crunchifyCompany));
                
                crunchifyLog("2) .hasItems() check");
                assertThat(company, hasItems("Crunchify.com"));
                
                crunchifyLog("3) .hasSize() check");
                assertThat(company, hasSize(3));
                
                assertThat(company.size(), is(3));
                
                crunchifyLog("4) .contains() and .containsInAnyOrder() check");
                assertThat(company, contains("Crunchify.com", "Google.com", "Facebook.com"));
                assertThat(company, containsInAnyOrder("Google.com", "Crunchify.com", "Facebook.com"));
                
                // FAIL
                // assertThat(company, contains("Google.com", "Crunchify.com", "Facebook.com"));
                
                crunchifyLog("5) .empty() check");
                assertThat(company, not(IsEmptyCollection.empty()));
                assertThat(new ArrayList<>(), IsEmptyCollection.empty());
                
        }
        
        private void crunchifyLog(String crunchifyText) {
                System.out.println(crunchifyText);
                
        }
        
        @Test
        public void crunchifyMapJUnitTests() {
                
                Map<String, String> company = new HashMap<>();
                company.put("C", "Crunchify.com");
                company.put("G", "Google.com");
                company.put("F", "Facebook.com");
                
                // Map: An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
                // This interface takes the place of the Dictionary class, which was a totally abstract class rather than an interface.
                Map<String, String> crunchifyCompany = new HashMap<>();
                crunchifyCompany.put("C", "Crunchify.com");
                
                // put(): Associates the specified value with the specified key in this map (optional operation).
                // If the map previously contained a mapping for the key, the old value is replaced by the specified value.
                // (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
                crunchifyCompany.put("G", "Google.com");
                crunchifyCompany.put("F", "Facebook.com");
                
                crunchifyLog("\n~~~~~~~~~~~ JUnit Map Check Test - All tests will PASS in our example ~~~~~~~~~~~");
                
                crunchifyLog("1) assertThat(company, is(crunchifyCompany) check");
                assertThat(company, is(crunchifyCompany));
                
                crunchifyLog("2) assertThat(company.size(), is(3)) check");
                assertThat(company.size(), is(3));
                
                crunchifyLog("3) .hasEntry() check which creates a matcher for Maps matching at least one entry whose key equals the specified key & value.");
                assertThat(company, IsMapContaining.hasEntry("C", "Crunchify.com"));
                assertThat(company, not(IsMapContaining.hasEntry("G", "Twitter.com")));
                
                crunchifyLog("4) .hasKey() creates a matcher for Maps matching at least one key that is equal to the specified key.");
                assertThat(company, IsMapContaining.hasKey("F"));
                
                crunchifyLog("5) .hasValue() creates a matcher for Maps matching at least one key that is equal to the specified value.");
                assertThat(company, IsMapContaining.hasValue("Crunchify.com"));
                
        }
        
        @SuppressWarnings("unchecked")
        @Test
        public void crunchifyObjectJUnitTests() {
                
                List<Company> list = Arrays.asList(new Company("Crunchify", 10), new Company("Google", 30000));
                
                assertThat(list, hasItems(new Company("Crunchify", 10), new Company("Google", 30000)));
                assertThat(list, containsInAnyOrder(new Company("Google", 30000), new Company("Crunchify", 10)));
                assertThat(list, containsInAnyOrder(hasProperty("name", is("Google")), hasProperty("name", is("Crunchify"))));
                
                crunchifyLog("\n~~~~~~~~~~~ JUnit Object Check Test Completed ~~~~~~~~~~~");
        }
        
        // Create Company Object
        public static class Company {
                
                public Company(String name, int employeeCount) {
                        this.name = name;
                        this.employeeCount = employeeCount;
                }
                
                private String name;
                private int employeeCount;
                
                public int getEmployeeCount() {
                        return employeeCount;
                }
                
                public void setEmployeeCount(int employeeCount) {
                        this.employeeCount = employeeCount;
                }
                
                public String getName() {
                        return name;
                }
                
                public void setName(String name) {
                        this.name = name;
                }
                
                // Test equal, override equals() and hashCode()
                @Override
                public boolean equals(Object c) {
                        if (this == c)
                                return true;
                        if (c == null || getClass() != c.getClass())
                                return false;
                        Company fruit = (Company) c;
                        return employeeCount == fruit.employeeCount && Objects.equals(name, fruit.name);
                }
                
                @Override
                public int hashCode() {
                        return Objects.hash(name, employeeCount);
                }
        }
        
        @Test
        public void crunchifyNullCheckJUnitTest() {
                
                // Two ways to check isNull
                assertThat(null, is(nullValue()));
                assertThat(null, is(IsNull.nullValue()));
                
                // Two ways to check isNotNull
                assertThat("crunchify", is(notNullValue()));
                assertThat("crunchify", is(IsNull.notNullValue()));
                
                crunchifyLog("\n~~~~~~~~~~~ JUnit Null Check Test Completed ~~~~~~~~~~~");
        }
        
}

Eclipse console output:

Just run above program as a Java Application and you should see result like below.
~~~~~~~~~~~JUnit Object Check Test Completed~~~~~~~~~~~

~~~~~~~~~~~JUnit Null Check Test Completed~~~~~~~~~~~

~~~~~~~~~~~JUnit List Check Test~~~~~~~~~~~
1) assertThat(company, is(crunchifyCompany)) check
2) .hasItems() check
3) .hasSize() check

~~~~~~~~~~~JUnit List Check Test~~~~~~~~~~~
1) assertThat(company, is(crunchifyCompany)) check
2) .hasItems() check
3) .hasSize() check
4) .contains() and .containsInAnyOrder() check
5) .empty() check

~~~~~~~~~~~ JUnit Map Check Test - All tests will PASS in our example ~~~~~~~~~~~
1) assertThat(company, is(crunchifyCompany) check
2) assertThat(company.size(), is(3)) check
3) .hasEntry() check which creates a matcher for Maps matching at least one entry whose key equals the specified key & value.
4) .hasKey() creates a matcher for Maps matching at least one key that is equal to the specified key.
5) .hasValue() creates a matcher for Maps matching at least one key that is equal to the specified value.

~~~~~~~~~~~ JUnit Object Check Test Completed ~~~~~~~~~~~

~~~~~~~~~~~ JUnit Null Check Test Completed ~~~~~~~~~~~

Process finished with exit code 0
hamcrest-java-junit-test-result
Let us know if you face any issue running above program.

The post How to use Hamcrest assertThat() Matchers to Create JUnit testcases in Java – Complete Tutorial appeared first on Crunchify.

Enregistrer un commentaire

0 Commentaires