Getting Started with AssertJ and HamCrest Frameworks

September 30, 2018 

Getting Started with AssertJ and HamCrest Frameworks

What is AssertJ and HamCrest?

With assertions, validate if something is working correctly or not, one can validate the response to check the functionality of the component. There are two of the most popular Java assertion frameworks which are available in the market and also these are open source. These frameworks are AssertJ and Hamcrest.

AssertJ is Java library that provides an interface for writing assertions. Test code readability and make maintenance of tests easier are the main goals of AssertJ. AssertJ is not as much popular as Hamcrest, but its popularity has been growing very fast in the last few years.

Hamcrest is one of the well known Java frameworks used for writing tests used for writing matcher objects, which are logically equal to "assertions." Due to its high popularity, later ported to other programming languages like C++, C#, Python, ActionScript 3, Objective C, PHP, JavaScript, R, and Erlang.


How AssertJ and HamCrest Work?

 

Hamcrest Overview

Add below dependency in your maven project in a pom.xml file.




   org.hamcrest

   java-hamcrest

   {version}

   test



Basic example -


import static org.hamcrest.MatcherAssert.assertThat;

import static org.hamcrest.Matchers.*;

import junit.framework.TestCase;

public class TeaTest extends TestCase {

 public void testEquals() {

   Tea yoursTea = new Tea("Ginger");

   Tea myTea = new Tea("Ginger");

   assertThat(yoursTea, equalTo(myTea));

 }

}

Syntax -


// Simple Assertions

assertThat(a, equalTo(b));

// Dates Assertions

assertThat(tomorrow, isAfter(today));

// List Assertions

assertThat(list, Matchers.> allOf(CoreMatchers.hasItem("a"),

      CoreMatchers.not(CoreMatchers.hasItem("b"))

));

// Null Assertions

assertThat(a, nullValue());

// Assertions With a Custom Message

assertThat("Error", a, equalTo(b));


Getting Started with AssertJ and HamCrest

Add below dependency in your maven project in a pom.xml file.




 org.assertj

 assertj-core

 {version}

 test


Syntax -


// Simple Assertions

assertThat(a).isEqualTo(b);

// Dates Assertions

assertThat(tomorrow).isAfter(today);

// List Assertions

assertThat(list).       

      contains("a").

      doesNotContain("b");

// Null Assertions

assertThat(actual).isNull();

// Assertions With a Custom Message

assertThat(a).isEqualTo(b).overridingErrorMessage("Error");

AssertJ and Hamcrest Examples

Below are some examples which show the similarities and differences of the common assertions between AssertJ and Hamcrest -


// Equality

assertThat(actual, equalTo(expected)); // Hamcrest

assertThat(actual).isEqualTo(expected); // AssertJ

// Null checking

assertThat(actual, nullValue()); // Hamcrest

assertThat(actual).isNull(); // AssertJ

// Boolean checks

assertThat(actual, is(true)); // Hamcrest

assertThat(actual).isTrue(); // AssertJ

// Double comparisons

assertThat(actualDouble, closeTo(expectedDouble, error)); // Hamcrest

assertThat(actualDouble).isCloseTo(expectedDouble, Offset.offset(offset)); // AssertJ

// Assume/Assumption (JUnit’s skipping behavior)

assumeThat(actual, equalTo(expected)); // Hamcrest

// n/a                           AssertJ

​

// Expect (fail-at-end)

// n/a                           Hamcrest

softly.assertThat(actual).isEqualTo(expected); //AssertJ
​

Benefits of Adopting AssertJ and HamCrest

There are some benefits of these Java assertion frameworks which are defined below -

  • Quality of code
  • Easy to find bugs
  • Facilitates changes
  • Simplifies Integration
  • Debugging

Why AssertJ and Hamcrest Matters?

There are many key points which explained that why these frameworks matters.

Readability - Both frameworks feel more natural and are easily readable and understandable as compared to others. Let's take an example of assertion.


assertEquals(expected, actual);

The above is a common way, the expected value is passed as the first argument and the actual value is passed as the second argument. But this method is very confusing until one can get used to it. But in the case of these two frameworks, the actual value is passed the as the first argument and the expected value is passed as the second argument, which is the biggest hurdle to get over.


assertThat(actual, equalTo(expected)); // Hamcrest

assertThat(actual).isEqualTo(expected); // AssertJ

Better Failure Messages - Much better error messages. In most of the other frameworks, the problem is that the assertion error does not report the expected values and actual values. Let's see an example -


assertTrue(expected.contains(actual));

java.lang.AssertionError

It doesn't provide the clearance of the error message but below code snippet provides a better explanation of an error which saves the time and hassle of a developer.


assertThat(actual, containsString(expected));

java.lang.AssertionError

Expected: a string containing abc

got: "def"

Custom Messages - Can also use assertions with custom messages in case of AssertJ and Hamcrest. Can also pass any user-defined message. Let's take an example -


assertThat("Error", a, equalTo(b)); // Hamcrest

assertThat(a).isEqualTo(b).overridingErrorMessage("Error"); // AssertJ

Portability - In case of Hamcrest, portability is also the advantage of its library. It can be used with both JUnit and Testing.

Type Safety - Another advantage of these assertThat is that it is type-safe. It does not allow comparing of different types. Let's take an example -


assertEquals("abc", 123); //compiles, but fails

assertThat(123, is("abc")); //does not compile

How to Adopt AssertJ and HamCrest?

Add the dependency according to the particular framework in pom.xml file.


// Hamcrest



   org.hamcrest

   java-hamcrest

   {version}

   test



// AssertJ


 org.assertj

 assertj-core

 {version}

 test


Import dependencies

Below are the basic examples -


// Hamcrest

@Test

   public void hamcrestTestExample() throws Exception {

       // Given

       Integer number = 5;

​

       // Then

       assertThat(number, greaterThan(3));

   }

// AssertJ

@Test

   public void assertJTestExample() throws Exception {

       // Given

       Integer number = 5;

​

       // Then

      assertThat(number).isGreaterThan(3);

   }

Concluding AssertJ and Hamcrest Frameworks

When the comparison is made between AssertJ and Hamcrest by popularity, Hamcrest is much more popular as compared to AssertJ. But when we compare by commits, AssertJ has a more stable development pattern in the last years. On comparing the both Google Trends found that Hamcrest is much more popular.

The primary purpose is to tell about the most popular Java assertion frameworks available in the market. Can use any one of these two frameworks, to extend the capabilities of the standard assertions use any of the frameworks between these two. Each programming language has its libraries for assertions which help users to implement different kinds of assertions easily.