JUnit assertEquals example
1. Introduction
To follow through with my previous post about assertTrue
and assertFalse
, this post will tackle on checking for an equality of a conditional statement on the test cases.
There is a method called assertEquals
in the JUnit library that can be used to check if two objects is equally defined or not. It can be used to check if a specific instance of an object is expected on a method called by the test, or if na object passed through a method was “polymorphed” correctly. This is to ensure that an object, decorated or not will have the same base properties as it is expected.
See the code example below.
2. The Source
JUnitAssertEqualExample.java
package com.areyes1.jgc.junit.assertequals; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class JUnitAssertEqualsExample { private JUnitAssertEqualsServiceExample junitAssertEqualsServiceSample; private ServiceObject serviceObject; @Before public void setData() { serviceObject = new ServiceObject(); junitAssertEqualsServiceSample = new JUnitAssertEqualsServiceExample(); junitAssertEqualsServiceSample.initiateMetaData(serviceObject); } @Test public void testAssertEqualsFalse() { // processed the item ServiceObject newServiceObject = new ServiceObject(); junitAssertEqualsServiceSample.initiateMetaData(newServiceObject); junitAssertEqualsServiceSample.processObject(serviceObject); assertEquals(serviceObject,newServiceObject); } @Test public void testAssertEquals() { junitAssertEqualsServiceSample.processObject(serviceObject); assertEquals(serviceObject,this.serviceObject); } @Test public void testAssertEqualsWithMessage() { junitAssertEqualsServiceSample.processObject(serviceObject); assertEquals( "Same Object", serviceObject,serviceObject); } @Test public void testAssertEqualsFalseWithMessage() { ServiceObject newServiceObject = new ServiceObject(); junitAssertEqualsServiceSample.postProcessing(serviceObject); assertEquals( "Not the Same Object", newServiceObject,serviceObject); } }
The assertEquals
is basically a function that takes two objects and see if they have the same instance object being used. The Example as shown above has 4 set of test that regresses the assertEquals. It checks for the same object that was processed and see if it’s still the same object in term of it’s instance, as it was passed before. A test case if the object used has a different one, and samples with messages in it.
Running this example will give you an output in Eclipse.
3. Download the Eclipse project
This was an example of JUnit assertEquals
source.
You can download the full source code of this example here: junit-assertequals-example