JUnit assertEquals example

Junit 5’s org.junit.jupiter.Assertions class provides different static assertions method to write test cases.

Please note that you need to use JUnit’s org.junit.Assert class in case of JUnit 4 or JUnit 3 to assert using assertEquals method.

[toc]

assertEquals usage

Assertions.assertEquals() checks if expected and actual are equal. In case, both are not equal, it will through AssertError.
Please also note that If both are null, they are considered equal.

When you call assertEquals(object1, object2), it use equals method of that type of Object.

For example:
if object1 and object2 are of String type, then String’s equals method will be called to determine equality relation.

String str1="India";
String str2=new String("India")
Assertions.assertEquals(str1,str2);

In case of Custom objects, it will use custom object’s equals method to determine equality. In case, it does not override equals method, it will use default behaviour of object class i.e. Object identity.

If object1 and object2 are primitives such as boolean, int , long and object1 and object2 will converted to corresponding wrapper classes and object1.equals(object2) will be used.

Floating point Assertions

When you want to compare floating points such as double and float, then you should always use extra parameter delta to avoid rounding off issues while comparing floating points.

public static void assertEquals(double expected, double actual, double delta)

assertEquals overloaded methods

public static void assertEquals(short expected,short actual)
public static void assertEquals(short expected, short actual,String message)
public static void assertEquals(short expected,short actual,Supplier messageSupplier)public static void assertEquals(byte expected,byte actual)
public static void assertEquals(byte expected, byte actual,String message)
public static void assertEquals(byte expected,byte actual,Supplier messageSupplier)public static void assertEquals(int expected,int actual)
public static void assertEquals(int expected, int actual,String message)
public static void assertEquals(int expected,int actual,Supplier messageSupplier)public static void assertEquals(long expected,long actual)
public static void assertEquals(long expected, long actual,String message)
public static void assertEquals(long expected,long actual,Supplier messageSupplier)

public static void assertEquals(char expected,char actual)
public static void assertEquals(char expected, char actual,String message)
public static void assertEquals(char expected,char actual,Supplier messageSupplier)

public static void assertEquals(float expected,float actual)
public static void assertEquals(float expected, float actual,String message)
public static void assertEquals(float expected,float actual,Supplier messageSupplier)
public static void assertEquals(float expected, float actual, float delta)
public static void assertEquals(float expected, float actual, float delta, String message)
public static void assertEquals(float expected, float actual, float delta, Supplier messageSupplier)

public static void assertEquals(double expected,double actual)
public static void assertEquals(double expected, double actual,String message)
public static void assertEquals(double expected,double actual,Supplier messageSupplier)
public static void assertEquals(double expected, double actual, double delta)
public static void assertEquals(double expected, double actual, double delta, String message)
public static void assertEquals(double expected, double actual, double delta, Supplier messageSupplier)

public static void assertEquals(Object expected,Object actual)
public static void assertEquals(Object expected, Object actual,String message)
public static void assertEquals(Object expected,Object actual,Supplier messageSupplier)

assertEquals example

Here is simple example

package org.arpit.java2blog;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
 
public class AssertEqualsTest {
 
	AssertEqualsTest aet;
	
	@BeforeEach
	public void beforeEachTest()
	{
		aet = new AssertEqualsTest();
	}
	
	public double getSquareRoot(double num)
	{
		return Math.sqrt(num);
	}
     
    /*
     * Examples for assertEquals
     */
    
    //public static void assertEquals(double expected, double actual,String message)
    @Test
    public void testSquareRootOf25(){
    	double squareRoot25 = aet.getSquareRoot(25.0);
    	Assertions.assertEquals(5.0, squareRoot25,"5 should be sqaure root of 25");
    }
    
  //public static void assertEquals(double expected, double actual,String message)
    @Test
    public void testSquareRootOf5(){
    	double squareRoot5 = aet.getSquareRoot(5.0);
    	Assertions.assertEquals(2.236, squareRoot5,"Square root of 5 is incorrect");
    }
    
  //public static void assertEquals(double expected, double actual,double delta, String message)
    @Test
    public void testSquareRootOf5WithDelta(){
    	double squareRoot5 = aet.getSquareRoot(5.0);
    	Assertions.assertEquals(2.236, squareRoot5,0.001,"Square root of 5 is incorrect");
    }
}

When you run above testcase, you will get below output:
assertEqualsTestOutput

Let’s understand output of each testcase:


testSquareRootOf25 – Pass

As 5 should be square root of 25, so this testcase will pass.


testSquareRootOf5 – Fail

As square root of 5 is 2.23606797749979 and not 2.236, so this testcase will fail.


testSquareRootOf5WithDelta – Pass

As square root of 5 is 2.23606797749979 within delta range of 0.0001 with respect to 2.236, so this testcase will pass.


JUnit assertEquals custom object example
Let’s use assertEquals to compare custom object.

Create a simple class named Country.

package org.arpit.java2blog.model;
 
public class Country{
	
	String name;
	long population;
	
	public Country(String name, long population) {
		super();
		this.name = name;
		this.population = population;
	}
	
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		result = prime * result + (int) (population ^ (population >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Country other = (Country) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (population != other.population)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return name +"-"+population;
	}

	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public long getPopulation() {
		return population;
	}
	public void setPopulation(long population) {
		this.population = population;
	}
}

Create another class named CountryHelper which have a method to return highest populated Country.This is the method we are going to test.

package org.arpit.java2blog.model;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CountryHelper {

	public Country getHighestPopulatedCountry(List countries)
	{
		Collections.sort(countries, new Comparator() {

			@Override
			public int compare(Country c1, Country c2) {
				return ((Long)c2.getPopulation()).compareTo(c1.getPopulation());
			}
		});
		return countries.get(0);
	}
	
}

Let’s create our testcase now.

package org.arpit.java2blog;

import static org.junit.jupiter.api.Assertions.assertEquals;

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

import org.arpit.java2blog.model.Country;
import org.arpit.java2blog.model.CountryHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class AssertEqualCustomObjectTest {

    CountryHelper ch;
    
    @BeforeEach
    public void beforeEachTest()
    {
        ch=new CountryHelper();
    }
    
    @Test
    public void testHighestPopulatedCountry(){
        
        Country india=new Country("India",20000);
        Country china=new Country("China",40000);
        Country bhutan=new Country("Bhutan",3000);
        Country nepal=new Country("Nepal",7000);
        List<Country> countries=new ArrayList<Country>();
        countries.add(india);
        countries.add(china);
        countries.add(bhutan);
        countries.add(nepal);
    
        assertEquals(china, ch.getHighestPopulatedCountry(countries));
        
    }
}

When you run above testcase, you will get below output.
AssertEqualsCustomObjectTestOutput
As you can see, we are comparing two countries objects with the help of assertEquals method and As china has highest population, this testcase will pass.
That’s all about Assertions.assertEquals()

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

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

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.