JUnit Assert is a core feature of the JUnit testing framework used in Java. They are essential for writing effective and reliable automated tests.
Overview
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.
What is assertEquals?
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.
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.
Advantages of Using Assertions
- Early Bug Detection
- Improved Software Reliability
- Enhanced Code Quality
- Faster Test Execution
- Supports TDD Process
- Validates Expected Outcomes
This article covers JUnit assert in detail for a comprehensive understanding.
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.
Read More: Unit testing in Java with JUnit
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 Methods | Purpose |
---|---|
assertEquals | Verifies if two values are equal |
assertTrue | Verifies if a given condition is satisfied |
assertFalse | Verifies if the condition is false |
assertNotEquals | Verifies if two values are not equal |
assertNull | Verifies if the given object is null or not |
assertNotNull | Verifies if the given object is not a null |
assertSame | Verifies if references the same object |
assertNotSame | Verifies if references do not point to the same object |
assertArrayEquals | Verifies if two arrays are equal |
assertThrows | Verifies that code block throws an exception of specified type |
assertTimeout | Verifies 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.
Read More: Understanding JUnit assertions
Working of Java assertEquals
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.
Common Scenarios for Using assertEquals
The assertEquals method is mostly used in unit testing frameworks like JUnit in Java or unittest in Python to compare the expected and actual values in a test case. Given below are some scenarios where assertEquals is usually used:
1. Validating Return Values
To verify if a function expected result for a given input:
Example:
assertEquals(4, Calculator.add(2, 2));
2. Checking Default Values
Upon initialization, check if an object or variable has the correct default value.
Example:
assertEquals("Guest", user.getName());
3. Testing String Outputs
To check if the correct string is returned or displayed.
Example:
assertEqual(format_name("john", "doe"), "John Doe")
4. Validating List or Array Contents
To compare expected vs actual collections, specifically when order matters.
Example:
assertEquals(Arrays.asList(1, 2, 3), actualList);
5. Comparing Calculated Results
To verify calculation accuracy
Example:
assertEquals(9.99, invoice.getTotal(), 0.01); // with delta for float comparison
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.
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.
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
Floating point assertions
Floating point assertions are powerful assertions in JUnit that verify precision digits. They are helpful where the fractions make a big difference in functionality…..Output
assertEquals for Primitive Data Types
Here’s how you can use assertEquals to check if two primitive values (like int, boolean, float, etc.) are equal.
Example (in Java using JUnit):
int expected = 10; int actual = Calculator.multiply(2, 5); assertEquals(expected, actual);
assertEquals for Objects in Java
When assertEquals(expected, actual) for objects in JUnit is used, it checks if the two objects are equal based on their .equals() method and not their memory reference.
Example:
User expectedUser = new User("Alice", 25); User actualUser = userService.getUserById(1); assertEquals(expectedUser, actualUser);
Here, assertEquals passes only if expectedUser.equals(actualUser) returns true. the equals() (and usually hashCode()) methods in your class should be overridden.
Read More: Understanding Assertions in Chai
assertEquals with Custom Messages
Add a custom failure message to assertEquals for making test failures more informative.
Syntax
assertEquals(String message, expected, actual);
Example:
int expected = 10; int actual = Calculator.add(4, 5); assertEquals("Sum should be 10", expected, actual);
If the test fails, the error would be:
java.lang.AssertionError: Sum should be 10 expected:<10> but was:<9>
Read More: Understanding Playwright Assertions
AssertEquals in JUnit 4 and JUnit 5: Differences
The assertEquals method implies that two values are equal in tests, both in JUnit 4 and JUnit 5. However, there are a few differences in how assertEquals is used between JUnit 4 and JUnit 5:
Feature | JUnit 4 | JUnit 5 |
---|---|---|
Import | org.junit.Assert.assertEquals | org.junit.jupiter.api.Assertions.assertEquals |
Message Order | assertEquals(message, expected, actual) | assertEquals(expected, actual, message) |
Lazy Message | Not supported | Supported: () -> “message” |
Example of AssertEquals in JUnit 4
assertEquals("Mismatch", 10, value);
Example of AssertEquals in JUnit 5
assertEquals(10, value, "Mismatch"); assertEquals(10, value, () -> "Mismatch: " + value); // Lazy eval
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()
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.
Feature | assertEquals() | assertSame() |
---|---|---|
Compares | Values/content (.equals()) | References/identity (==) |
Suitable for | Logical equality | Object identity |
Passes with | Different objects, same value | Only if both refer to same object |
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
Read More: What is Assertion Testing?
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.
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.
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.
Useful Resources for JUnit
- How to run JUnit 4 Test Cases in JUnit 5
- JUnit Testing Tutorial: JUnit in Java
- How to write JUnit test cases
- How to Ignore a Base Test Class in JUnit
- How to run JUnit Parameterized Test in Selenium
- Understanding JUnit assertions for Selenium Testing with Examples
- Test Automation using JUnit Annotations and Selenium
- How to create JUnit Test Suite? (with Examples)
- Unit Testing in Java with JUnit
- JUnit vs NUnit: Framework Comparison
- JUnit Vs TestNG