Master JUnit Asserts for Reliable Unit Testing

Learn how to use JUnit asserts effectively for robust unit testing in Java. Master the key assert methods to enhance your test reliability and code quality.

Get Started free
Home Guide Junit Assert

Junit Assert

By GH, Community Contributor -

JUnit is a popular Java-based, open-source testing framework. It is widely used for various testing, such as unit testing, component testing, integration testing, and end-to-end testing.

It provides strong assertions to compare actual and expected test results, ensuring your code works as intended. With seamless integration into all major IDEs, getting started with JUnit is easy—just import the packages and create your test classes and methods. JUnit supports both Test-Driven Development (TDD) and Behavior-Driven Development (BDD), with JUnit Cucumber being a top choice for BDD in functional and API testing. For Java developers, JUnit is essential for validating application functionality, offering a range of methods to confirm test outcomes.

What is JUnit Assert?

JUnit Assert is a class or core component of JUnit. It is a static class that provides many methods to validate the conditions. If the condition is satisfied, JUnit marks the test as pass, and if it doesn’t satisfy the given condition, it marks the test as fail. JUnit Assert is used to validate the behavior of the code or component under the test to ensure that it meets the given requirements. 

JUnit Assert Methods

JUnit provides many methods to validate the conditions. Each one of them is designed for a specific purpose; some of the popular JUnit Assert methods are given below.

JUnit Assert MethodsPurpose
assertEqualsVerifies if two values are equal
assertTrueVerifies if a given condition is satisfied
assertFalseVerifies if the condition is false
assertNotEqualsVerifies if two values are not equal
assertNullVerifies if the given object is null or not
assertNotNullVerifies if the given object is not a null
assertSameVerifies if references the same object
assertNotSameVerifies if references do not point to the same object
assertArrayEqualsVerifies if two arrays are equal
assertThrowsVerifies that code block throws an exception of specified type
assertTimeoutVerifies if the given code block completes the execution in the given timeout

What is assertEquals in Java?

assertEquals is the most widely used method in the JUnit Testing Framework. It compares the actual and expected values of the given type and marks the test as pass or fail. Many variations are available for the assertEquals methods, such as the method that compares int, double, object, string, etc.

Why is Java assertEquals used?

assertEquals compares the values of different data types, such as string, integer, double, object, etc., as part of component or functional testing and decides the outcome of test cases in automation testing. It accepts two values of a supported data type; if they don’t match, the test will be marked as failed by indicating the values mismatch.

What are the Advantages of using Assertions?

Assertions have many advantages, including software quality, reliability, early bug detection, and code quality. Key advantages are mentioned below:

  • Assertions in Unit testing uncover defects in the early stages that arise during software development. Unit testing focuses on path coverages, logical errors, etc.
  • Assertions in automated functional testing validate the expected and actual results, reducing the manual testing effort and increasing the speed of product delivery.
  • It aids the TDD process, in which tests are written before the code, and the code should pass those tests to match the given requirements.
  • It improves the code quality as assertions act as a quality gate.
  • Assertions can help enforce quality gates such as SonarCloud during the deployment process.

Read More: JUnit vs TestNG

What are the Syntax and Parameters of assertEquals?

As mentioned earlier, assertEquals has many variations or overloads to support different data types.

assertEquals Basic Syntax

assertEquals(expected,actual)

expected: the expected value of a specific type such as int, String, object, etc.

actual: The value fetch from the code under test

Example: assertEquals(x,y)

assertEquals with Custom Message 

assertEquals(String message, expected, actual);

message: The custom message that displays if assert fails. 

Example: assertEquals(“This is not expected”, x, y)

assertEquals for Object comparison

assertEquals(Object expected, Object actual);

Floating-Point Comparison

assertEquals(double expected, double actual, double delta);

delta: delta is the maximum allowed difference between expected and actual values for floating point precision.

Example of JUnit assertEquals

Consider an example of a string comparison using the assertEquals() method

package org.example;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AssertEqualsDemoTest {

    @Test

    public  void assertEqualTest() {

        String s1 = new String("Browserstack");

        String s2 = new String("Browserstack");

        assertEquals(s1, s2);

    }

}

In the above code, 

import static org.junit.Assert.assertEquals : Imports the static class of Assert with method assertEquals.

@Test: This is an annotation that indicates the given method is a JUnit Test.

Create two variables of the data type string, s1 and s2. Both contain the same String but different objects.

assertEquals(s1, s2): The JUnit method compares whether two strings have the same value.

In the given example, two string variables have having same values, so the assertion will pass.

Test passed

Modify the values of the string as mentioned below

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AssertEqualsDemoTest {

    @Test

    public  void assertEqualTest() {

        String s1 = new String("Browserstack Testing tool");

        String s2 = new String("Browserstack");

        assertEquals(s1, s2);

    }

}

After executing the above test method, JUnit fails the test by highlighting the differences, as shown below.

Assertequals Demo test

Floating point assertions are powerful assertions in JUnit that verify precision digits. They are helpful where the fractions make a big difference in functionality. Direct comparison may fail due to rounding or precision issues. To overcome such challenges, JUnit provides a tolerance range called a delta. Below is the summary.

  • Floating point assertions help to verify the precision digits
  • JUnit provides the delta parameter to avoid precision errors to allow the difference between actual and expected values
  • Floating point assertions help to increase the reliability of critical systems
  • Floating point assertion can help in testing edge-case scenarios
  • It can verify the accuracy of scientific computations, graphics processing, etc.

Floating point assertions  basic syntax

assertEquals(double expected, double actual, double delta)

expected: expected floating point precision value

actual: floating point value fetched by code under test

delta: maximum allowed differences between actual and expected value

Floating point assertions overload with custom message

assertEquals(String message, double expected, double actual, double delta)

message: Custom message to display when floating point assertion fails

expected: expected floating point precision value

actual: floating point value fetched by code under test

delta: maximum allowed differences between actual and expected value

Example of floating-point assertions

package test.org.example;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

public class AssertEqualsDemoTest {

    @Test

    public  void assertEqualFloatingPointAssertionTest() {

        double expectedPI = 3.142;

        double actualPI = 3.143;

        assertEquals(actualPI,expectedPI,0.001); //Passes

    }

    @Test

    public  void assertEqualFloatingPointAssertionCustomMessageTest() {

        double expectedPI = 3.142;

        double actualPI = 3.144;

        assertEquals("Not an expected PI value",actualPI,expectedPI,0.001); //Fails

    }

}

Output

AssertEquals floating point

assertEquals vs assertSame

Though the names assertEquals() and assertSame() look similar, JUnit has different implementations under the hood. assertEquals() makes a value comparison, and assertSame() makes a reference comparison. In the previous section, assertEquals() was explained with an example. 

What is assertSame()?

assertSame() method verifies if two objects point to the same reference. Rather than their values, it verifies the reference of the object.

Syntax:

assertSame(Object expected, Object actual);

expected: The expected object reference

actual: The actual object reference fetched by the code

Differences between assertEquals() and assertSame()

assertEquals() compares the two values / objects whereas assertSame() compares the references of two objects 

Example:

package test.org.example;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

import static org.junit.Assert.assertSame;

public class AssertDemoTest{

    @Test

    public void assertEqualTest() {

        String s1 = new String("Browserstack");

        String s2 = new String ("Browserstack");

        assertEquals(s1,s2); //Passes

    }

    @Test

    public void assertSameTest() {

        String s1 = new String("Browserstack");

        String s2 = new String ("Browserstack");

        assertSame(s1,s2); //Fails

    }

}

In the above code,

There are two string objects, namely s1 and s2. Both are different objects but contain the same value, “Browserstack“.

When you execute the test, the assertEqualTest() method passes because it validates the values inside the object. Whereas the assertSameTest() method fails because both reference different objects, indicating a mismatch in reference.

Output

Assertequlas assertsame

Using Selenium JUnit with BrowserStack

JUnit isn’t just for unit testing—it’s widely used for many types of testing, including functional, integration, and end-to-end. When paired with Selenium, it’s the industry standard for automation testing. Since automated tests can behave differently across platforms, browsers, and screen sizes, JUnit helps ensure your application works consistently everywhere by validating both actual and expected outcomes.

Though you have powerful automation code, automation cannot yield greater benefits if you do not test it across platform and browser combinations. BrowserStack Automate provides such a flexible cloud platform that contains various devices and browser combinations. Interestingly, it supports integration with many test automation tools, including the Selenium JUnit framework

Talk to an Expert

BrowserStack Automate can be used for cross-browser testing, responsive testing, visual comparison, and more. You can easily configure your existing Selenium JUnit tests by referencing Selenium with JUnit BrowserStack integration documentation and running your tests without modifying the existing test automation code.

Conclusion

Assertions are a fundamental aspect of any testing process, and JUnit stands as the most widely used assertion framework in Java-based application testing. As an open-source and extensible tool, JUnit provides a variety of assertions to ensure your application code is both accurate and reliable. 

BrowserStack Automate Banner

However, when it comes to functional test automation, ensuring consistent functionality across multiple platforms and browsers can be challenging. Setting up and maintaining such an environment can be both time-consuming and complex. 

BrowserStack Automate offers a cloud-based platform with access to thousands of real devices and browsers. With BrowserStack, you can easily integrate your existing Selenium JUnit tests by adding a few configuration options without altering your existing code. 

This simplifies the process of cross-device and cross-browser testing, enabling you to confidently release your code and ensure it works seamlessly across all environments.

Try BrowserStack Now

Tags
Automation Frameworks Automation Testing

Featured Articles

Understanding JUnit assertions for Selenium Testing with Examples

JUnit Vs TestNG: Differences Between JUnit and TestNG

Supercharge Your JUnit Testing

Elevate your testing strategy with BrowserStack Automate. Seamlessly run JUnit tests across multiple devices and browsers for unparalleled test coverage.