Junit Assert & AssertEquals with Example

โšก Smart Summary

JUnit Assert and AssertEquals determine the pass or fail status of a test case by comparing expected and actual values. This resource explains the assert methods provided by org.junit.Assert, including boolean, null, identity, equality, and array assertions, with a complete working example.

  • โœ… Purpose: Assert methods from org.junit.Assert verify conditions and detect test failures.
  • ๐Ÿ”ข Method Types: Boolean, null, identical, equals, array-equals, and fail-message assertions cover common checks.
  • ๐ŸŸฐ assertEquals: Compares values using the equals() method, wrapping primitives into objects first.
  • ๐Ÿ”ฌ Floating Point: A delta tolerance is required when comparing float or double values.
  • ๐Ÿงช Example: A test class and runner demonstrate every key assert statement returning true.

JUnit Assert and AssertEquals

What is Junit Assert?

Assert is a method useful in determining the Pass or Fail status of a test case. The assert methods are provided by the class org.junit.Assert, which extends the java.lang.Object class.

There are various types of assertions, like Boolean, Null, Identical, etc.

JUnit provides a class named Assert, which provides a bunch of assertion methods useful in writing test cases and detecting test failures.

The assert methods are provided by the class org.junit.Assert, which extends the java.lang.Object class.

JUnit Assert methods

Boolean

If you want to test the boolean conditions (true or false), you can use the following assert methods:

  1. assertTrue(condition)
  2. assertFalse(condition)

Here the condition is a boolean value.

Null object

If you want to check the initial value of an object/variable, you have the following methods:

  1. assertNull(object)
  2. assertNotNull(object)

Here object is a Java object, e.g. assertNull(actual);

Identical

If you want to check whether the objects are identical (i.e., comparing two references to the same Java object) or different:

  1. assertSame(expected, actual) โ€” It will return true if expected == actual.
  2. assertNotSame(expected, actual)

Assert Equals

If you want to test the equality of two objects, you have the following method:

  • assertEquals(expected, actual)

It will return true if expected.equals(actual) returns true.

Assert Array Equals

If you want to test the equality of arrays, you have the following method:

  • assertArrayEquals(expected, actual)

The above method must be used if arrays have the same length. For each valid value for i, you can check it as given below:

  • assertEquals(expected[i], actual[i])
  • assertArrayEquals(expected[i], actual[i])

Fail Message

If you want to throw any assertion error, you have fail(), which always results in a fail verdict.

  • fail(message);

You can have an assertion method with an additional String parameter as the first parameter. This string will be appended to the failure message if the assertion fails. For example, fail(message) can be written as:

  • assertEquals(message, expected, actual)

JUnit assertEquals

You have assertEquals(a, b), which relies on the equals() method of the Object class.

  • Here it will be evaluated as a.equals(b).
  • Here the class under test is used to determine a suitable equality relation.
  • If a class does not override the equals() method of the Object class, it will get the default behaviour of the equals() method, i.e., object identity.

If a and b are primitives such as byte, int, boolean, etc., then the following will be done for assertEquals(a, b):

a and b will be converted to their equivalent wrapper object type (Byte, Integer, Boolean, etc.), and then a.equals(b) will be evaluated.

For example, consider the below-mentioned strings having the same values; let us test it using assertEquals:

String obj1 = "Junit";
String obj2 = "Junit";
assertEquals(obj1, obj2);

The above assert statement will return true as obj1.equals(obj2) returns true.

Floating point assertions

When you want to compare floating-point types (e.g., double or float), you need an additional required parameter, delta, to avoid problems with round-off errors while doing floating-point comparisons.

The assertion evaluates as given below:

  • Math.abs(expected โ€“ actual) <= delta

For example:

assertEquals(aDoubleValue, anotherDoubleValue, 0.001)

JUnit Assert Example

The below example demonstrates how to assert a condition using JUnit assert methods.

Let us create a simple test class named Junit4AssertionTest.java and a test runner class TestRunner.java.

You will create a few variables and important assert statements in JUnit.

In this example, you will execute our test class using TestRunner.java.

Step 1) Let us create a class covering all important assert statement methods in JUnit:

Junit4AssertionTest.java

package guru99.junit;

import static org.junit.Assert.*;
import org.junit.Test;

public class Junit4AssertionTest {

    @Test
    public void testAssert() {

        // Variable declaration
        String string1 = "Junit";
        String string2 = "Junit";
        String string3 = "test";
        String string4 = "test";
        String string5 = null;
        int variable1 = 1;
        int variable2 = 2;
        int[] airethematicArrary1 = { 1, 2, 3 };
        int[] airethematicArrary2 = { 1, 2, 3 };

        // Assert statements
        assertEquals(string1, string2);
        assertSame(string3, string4);
        assertNotSame(string1, string3);
        assertNotNull(string1);
        assertNull(string5);
        assertTrue(variable1 < variable2);
        assertArrayEquals(airethematicArrary1, airethematicArrary2);
    }
}

Step 2) You need to create a test runner class to execute the above class:

TestRunner.java

package guru99.junit;

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
    public static void main(String[] args) {
        Result result = JUnitCore.runClasses(Junit4AssertionTest.class);
        for (Failure failure : result.getFailures()) {
            System.out.println(failure.toString());
        }
        System.out.println("Result==" + result.wasSuccessful());
    }
}

Step 3) Let us analyse the expected output step by step. Consider all assert statements one by one:

  1. assertEquals(string1, string2);

Now compare string1=”Junit” with string2=”Junit” with the equals method of the Object class. Replacing the assertEquals method with the java.lang.Object.equals() method:

string1.equals(string2) => returns true

So assertEquals(string1, string2) will return true.

  1. assertSame(string3, string4);

The “assertSame()” functionality is to check that the two objects refer to the same object. Since string3=”test” and string4=”test”, both string3 and string4 are of the same type, so assertSame(string3, string4) will return true.

  1. assertNotSame(string1, string3);

The “assertNotSame()” functionality is to check that the two objects do not refer to the same object. Since string1=”Junit” and string3=”test”, both string1 and string3 are of different types, so assertNotSame(string1, string3) will return true.

  1. assertNotNull(string1);

The “assertNotNull()” functionality is to check that an object is not null. Since string1=”Junit”, which is a non-null value, assertNotNull(string1) will return true.

  1. assertNull(string5);

The “assertNull()” functionality is to check that an object is null. Since string5=null, which is a null value, assertNull(string5) will return true.

  1. assertTrue(variable1 < variable2);

The “assertTrue()” functionality is to check that a condition is true. Since variable1=1 and variable2=2, which shows that the variable1 < variable2 condition is true, assertTrue(variable1 < variable2) will return true.

  1. assertArrayEquals(airethematicArrary1, airethematicArrary2);

The “assertArrayEquals()” functionality is to check that the expected array and the resulting array are equal. The type of array might be int, long, short, char, byte, or java.lang.Object. Since airethematicArrary1 = { 1, 2, 3 } and airethematicArrary2 = { 1, 2, 3 }, which shows both arrays are equal, assertArrayEquals(airethematicArrary1, airethematicArrary2) will return true.

Since all seven assert statements of the Junit4AssertionTest.java class return true, when you execute the test assert class, it will return a successful test (see the output below).

Step 4) Right-click on Junit4AssertionTest.java and click on Run As -> JUnit. You will see the output as given below:

JUnit Assert Example

The above output shows a successful test result as expected.

FAQs

Yes. AI assistants can produce assertEquals, assertTrue, and other assertions from a method’s expected behaviour. You should still review the expected values and edge cases to ensure the tests are meaningful.

Yes. AI can suggest assertEquals versus assertSame or assertArrayEquals based on what you are comparing. This reduces common mistakes, such as checking references when you intended to compare values.

assertEquals checks value equality using the equals() method. assertSame checks that two references point to the exact same object in memory. Two equal-valued objects can fail assertSame.

When an assertion fails, JUnit throws an AssertionError, marks the test as failed, and reports the optional message along with the expected and actual values to help you debug the test.

Summarize this post with: