JUint Asserts and Matchers

Problem: JUnit tutorials are often written by testers with a reasonable amount of unit checking expertise

Why this post?

There are plenty of JUnit tutorials available online. They are often written by testers with a reasonable amount of unit checking experience. The problem is that experts and beginners see things differently. I began noticing that beginners often read these JUnit tutorials written by experts and come away feeling like there is a unsurmountable mountain of knowledge they need to learn before applying the concepts. So we decided to try something different – writing tutorials for beginners by beginners. Rupesh Mishra, a Qxf2 Services employee, volunteered to write this post. This is PART II in a series of posts that Rupesh is writing on JUnit. The rest of the post is written by Rupesh.

JUnit asserts and matchers

There are several JUnit assertion method and they all are static methods. All these methods are stored in Assert Class which is one of the important class of JUnit framework. We can easily import this class by

import static org.junit.Assert.*;

Using this Assert Class we can write set of useful assertion methods. Here is a list of all important methods of Assert Class.

Methods & Description
assertEquals(boolean expected, boolean actual);
Check that two primitives/Objects are equal
assertTrue(boolean expected, boolean actual);
Check that a condition is true
assertFalse(boolean condition)
Check that a condition is false
assertNotNull(Object object);
Check that an object isn’t null.assertNull(Object object)
Check that an object is null
assertSame(boolean condition);
The assertSame() methods tests if two object references point to the same objectassertNotSame(boolean condition)
The assertNotSame() methods tests if two object references not point to the same object.
assertArrayEquals(expectedArray, resultArray);
The assertArrayEquals() method will test whether two arrays are equal to each other.
assertThat(actual, matcher);
The assertThat() method will test whether actual satisfies the condition specified by matcher.

In this post I will discuss more about the assertThat() method using Hamcrest matcher library and how to write custom matchers. Before that lets take a quick look at the other assert methods.

  • assertEquals()

The assertEquals() method checks that two values are equal.Compared values may be of any Java type: Boolean,float,double,short,byte,char,int,long or object.

import static org.junit.Assert.*;
import org.junit.Test;
 
public class Practice_codeTest {
 
	@Test
	public void testEquals() {
		Practice_code InputString = new Practice_code();
                //Concatenating two words and storing in string variable "result".
		String result = InputString.concatenate("Practice","Code");
                //assertEquals("expected output","actual output" );
		assertEquals("PracticeCode", result);
	  }
}
  • assertTrue() and assertFalse()

assertTrue() and assertFalse() methods are use to check that a condition is True or False.

import static org.junit.Assert.*;
import org.junit.Test;
 
public class Practice_codeTest {
	//Method for return True if input number will even.
	public boolean isEvenNumber(int number){
 
        boolean result = false;
        if(number%2 == 0){
            result = true;
        }
        return result;
    }
 
	@Test
	public void testEvenNumbers() {
		Practice_codeTest newnumber = new Practice_codeTest();
		assertTrue(newnumber.isEvenNumber(4));
		assertFalse(newnumber.isEvenNumber(3));
	  }
}
  • assertNull() and assertNotNull()

The assertNull() and assertNotNull() methods will test whether the object value is null or not.

import static org.junit.Assert.*;
import org.junit.Test;
 
public class Practice_codeTest {
 
	Object firstnumber = null;//Declaring object firstnumber as a Null.
	Object secondnumber = 123;//Declaring object secondnumber with value 123 that means NotNULL.
	@Test
	public void testNullvalues() {
		assertNull(firstnumber);
		assertNotNull(secondnumber);
 
	  }
}
  • assertSame() and assertNotSame()

The assertSame() and assertNotSame() will check whether two objects points to the same object or not,If they will points to same object then only assertSame() method will pass otherwise only assertNotSame() method will pass.

import static org.junit.Assert.*;
import org.junit.Test;
 
public class Practice_codeTest {
 
	String firstnumber = new String("abc");//Declaring string firstnumber as a value "abc".
	String secondnumber = firstnumber;//Declaring string secondnumber and pointing to string firstnumber.
	String thirdnumber = new String("abc");//Declaring string thirdnumber as a new string with value "abc".
	@Test
	public void testSameString() {
		assertSame(firstnumber,secondnumber);
		assertNotSame(firstnumber,thirdnumber);	
	  }
}
  • assertArrayEquals()

The assertArrayEquals() method checks whether two arrays are equal to each other or not. It will test number of elements in both the arrays, order of the elements and if the elements in the two arrays are the same. Here is a example.

import static org.junit.Assert.*;
import org.junit.Test;
 
import java.util.Arrays;
 
public class Practice_codeTest {
 
	@Test
	public void testArrayEquals() {
		int[] numbers = {5,4,3,2,1};
                //Sorting array.
		Arrays.sort(numbers);
		int[] expectedOutput = {1,2,3,4,5};
                //assertArrayEquals("expected array","actual array" );
		assertArrayEquals(expectedOutput, numbers);
	  }
}
  • assertThat()

The assertThat() methods satisfies the condition specified by matcher. A matcher is an object that implements the org.hamcrest.matcher interface. Hamcrest is a framework for writing matcher objects that allow me to declare rules for tests whether a given object matches the criteria or not. Matchers improve flexibility and readability of the code. We can also define better failure messages. The Hamcrest library comes with numerous matchers included and also provides the facility to write your own Matcher. The most important Matchers of Hamcrest are the following:
is, equalTo, not, containsString, allof, anyof, hasProperty,closeTo, greaterThan
They all can be use by a static import of org.hamcrest.CoreMatchers .
Here is an example of some common matchers:

import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
 
public class TestFile {
 
	@Test
	public void MatchersExample() {
	    assertThat(123, is(123));
	    assertThat("book", equalTo("book"));
	    assertThat("book", not(equalTo("apple")));
	    assertThat("apple", containsString("e"));
	  }
}

Write Custom Matchers
For writing matchers I am going to create a new Class file CustomMatchers.java in the same package junitMatchers with my JUnit test file TestFile.java .
Here is my CustomMatchers.java in which i am creating a Custom Matcher EvenNumber ,which will check whether the number is even or not.

package junitMatchers;
 
import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
 
public class CustomMatchers extends TypeSafeMatcher<Integer> {
 
  @Override
  public boolean matchesSafely(Integer number) {
	  if (number % 2 != 0) {
		  return false;
		  }
	return true;
  }
 
  public void describeTo(Description description) {
    description.appendText("Given number is Even Number");
    // describe expectation.
  }
 
  @Factory
  public static <T> Matcher<Integer> EvenNumber() {
    return new CustomMatchers();
  }
}

The @Override annotation is use to declare intent to override a method and @Factory annotation is allowing to manually create my test instances.
To import this Matcher in my TestFile.java I will use this code:

import static junitMatchers.CustomMatchers.EvenNumber;

In this code junitMathers is Package name,CustomMatchers is Class File name and EvenNumber is the name of Matcher.

Here is my complete TestFile.java,which is using Custom Matcher EvenNumber to test Actual number is even or not.

package junitMatchers;
 
import static junitMatchers.CustomMatchers.EvenNumber;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
 
public class TestFile {
 
	@Test
	public void testEvenNumber() {
	    assertThat(4, is(EvenNumber()));
	    assertThat(3, is(not(EvenNumber())));
	  }
}

And that brings us to the end of the tutorial. Let us know if it helped having a beginner write for beginners.

Leave a Reply

Your email address will not be published. Required fields are marked *