JUnit - SPLessons

Assertion in JUnit

Chapter 10

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Assertion in JUnit

Assertion in JUnit

shape Introduction

This chapter demonstrate the Assertion in JUnit. In order to  describe various assertion techniques in JUnit test methods and describe about the built in mechanism, also following topics are covered.

  • Assertions
  • Hamcrest Matchers


shape Description

Assert is a class which provides some test methods for JUnit testing. The mechanism for built-in assertion of JUnit is given by the class org.junit.Assert. Following are the assertion in JUnit methods.

  • assertArrayEquals()
    The method is used to test the 2 Exhibits are proportionate to each other. Which implies both the arrays contain equal number of segments or not.
  • assertEquals()
    The method is used to analyzes equality between 2 articles.
  • assertTrue() and assertFalse()
    The method is used to test single variable value to be true or false.
  • assertNull() and assertNotNull()
    The method is used  to test a variable either it is null or not null.
  • assertSame() and assertNotSame()
    The method is used to test referance point for two items either its belongs to same object or not.
  • asssertFail()
    This method automatically fails by calling Fail.

shape Examples

The assertions uses a popular Java library Hamcrest to give the ability to use matchers to construct elegant Assertions in our tests. Below code demonstrate the Assertion in JUnit methods in a TrackingServiceTest.

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers;
import static org.junit.matchers.JUnitMtachers.*;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.After;
import org.junit.AfterClass;
import org.junt.exeperimental.categories.category;
import com.simpleprogram.proteintracker.InvalidGoalException;

import com.simpleprogram.proteintracker.TrackingService;
import static org.junit.Assert.*;

public class Trackingservice {
	private TrackingService service;
	public static void before()
		System.out.println("Before Class");
	public static void after()
		System.out.println("After Class");
	public void setUp()
		service = new TrackingService();
	public void tearDown()

	public void NewTrackingServiceTotalIsZero()
		assertEquals("Tracking service was not zero", 0, service.getTotal());

	public void WhenAddingProteinTotalIncresesByThatAmount()
		assertEquals(10, service.getTotal());
		assertThat(service.getToatal(), is(10))
	public void WhenRemovingProteinTotalRemainsZero()
		assertEquals(0, service.getTotal());

The below image display the output for the above code.

Hamcrest Matcher

shape Description

Hamcrest comprises of various jars coordinating the different needs of uses. This archive depicts these distributables and the Functionality contained in each of them. Hamcrest is a library which provides API’s for creating a flexible Expressions. Matcher is an external frame work adding Matchers to the frame work is known as Hamcrest and following are the different types of Matchers.

Chaining Matcher

shape Description

JUnit has some of the Matchers and those are divided into several types. Whenever Multiple Matchers are combined together is known as Chaining Matcher.

shape Examples

In the below code have the two Matchers not( is(786) ) here is() method returns one Matcher and not() method returns one Matcher.

public void testWithMatchers() {

    assertThat(456, not( is(786) ) );


Core Matchers

shape Description

JUnit has the some of the inbuilt matchers those are divided into several types and those methods elaborate the some of the properties. Click the official page of Assertion in JUnit.org to check the some of the Assertion in JUnit Matchers as shown in below image.

  • hasItems
    public static org.hamcrest.Matcher<java.lang.Iterable> hasItem(T element)
    The method is used to return a matcher that matches various collections containing elements.
  • everyItem
    public static org.hamcrest.Matcher<java.lang.Iterable> everyItem(org.hamcrest.Matcher elementMatcher)
    The method return matchers for various collections where every element get metched with elementMatcher.
  • containsString
    public static org.hamcrest.Matcher <java.lang.String>containsString(java.lang.String substring)
     A method returns the matcher that matches a string containing substring.
  • both
    public static <T>org.junit.internal.matchers.CombinableMatcher<T> both(org.hamcrest.Matcher matcher<T>matcher)
    The method is sued for combining two matchers and must pass the both matchers.
  • either
    public static <T>org.junit.internal.matchers.CombinableMatcher <T>either(org.hamcrest.Matcher <T>matcher)
    The method is used for combining two matchers and either of the matcher may pass.

Custom Matchers

shape Description

User can create own Matchers and plug into the assertThat() method the below code demonstrate the Custom Matcher.

shape Examples

The Basematcher class can be implement by adding new methods and subclasses get those methods automatically shown in below code.

public static Matcher matches(final Object expected){

    return new BaseMatcher() {

        protected Object theExpected = expected;

        public boolean matches(Object o) {
            return theExpected.equals(o);

        public void describeTo(Description description) {

Using of the Custom Matcher is shown below.

public void testThat() {
    MyUnit myUnit = new MyUnit();

    assertThat(myUnit.getTheSameObject(), matches("constant string"));



shape Key Points

  • Assertion in JUnit are imported from the org.junit.Assert
  • Hamcrest is a library which contain all APIs of Junit.
  • Core Matchers are available in JUnit.
  • Custom matchers can plug into the assertThat method.