Run Web Automation Tests at Scale with Agentic AI

Generate tests with AI agents or automate test suites with Selenium, Playwright and other frameworks. Run tests in parallel on TestMu AI scalable cloud grid.

AutomationSelenium TutorialTutorial

JUnit Assertions: assertEquals, assertThrows, assertAll

Learn the various JUnit assertion methods in Selenium testing, focusing on the assertTrue() method in JUnit.

Last Updated on:

JUnit assertions confirm whether a Selenium test's actual result matches its expected outcome, using methods such as assertEquals(), assertTrue(), and assertFalse(). JUnit groups these checks into hard assertions, which stop a test immediately on failure, and soft assertions, which let the rest of the script keep running with assertAll(). This guide covers the types of assertions, each JUnit assert method with examples, third-party assertion libraries, and how AI tools now help write and check them.

Overview

To validate Selenium test outcomes, use JUnit hard assertions like assertEquals() to halt execution immediately upon failure, or use soft assertions with assertAll() to continue running tests. For advanced, expressive validations, integrate third-party libraries like AssertJ or Hamcrest.

  • Best for equality validation: assertEquals() compares the expected result with the actual result in Selenium scripts, halting execution and throwing an assertion error if they do not match.
  • Best for validating true conditions: assertTrue() confirms that a given boolean condition evaluates to true, such as verifying if a button is visible or a URL is correct during a test.
  • Best for validating false conditions: assertFalse() verifies that a specified boolean condition evaluates to false, throwing an assertion error and terminating execution if the condition is true.
  • Best for verifying null references: assertNull() ensures that a passed object contains a null value, throwing an assertion error if the object is not null.
  • Best for verifying non-null objects: assertNotNull() checks that a provided object does not hold a null value, failing the test if a null reference is encountered.
  • Best for comparing memory references: assertSame() verifies that two objects refer to the exact same instance in memory, throwing an error if they point to different instances.
  • Best for verifying distinct instances: assertNotSame() ensures that two objects do not refer to the same instance in memory, comparing object references rather than their values.
  • Best for soft assertions: assertAll() enables soft assertions in Selenium, allowing multiple page elements to be verified without halting execution, throwing accumulated errors only at the end of the test.
  • Best for fluent assertions: AssertJ provides advanced, fluent assertion capabilities and collection validations that make test assertions more expressive and readable than standard JUnit methods.
  • Best for matcher-based assertions: Hamcrest offers advanced assertion capabilities, including detailed error messages and expressive syntax, to improve the readability of complex test validations.
  • Best for analyzing test failures: KaneAI is a GenAI native test agent from TestMu AI that analyzes browser-specific assertion failures and provides actionable insights to resolve issues.

What Are Assertions?

Assertions in software testing are statements that verify expected outcomes during test execution. Assertions act as a checkpoint between actual and anticipated results, which helps in the early detection of issues and improves the reliability of the overall software testing life cycle.

Open-source test automation frameworks like Selenium have enabled web testing at scale, and assertions are what let a script confirm whether that testing actually passed. If you are preparing for an interview, you can learn more through Selenium interview questions.

Types of Assertions

There are two types of assertions for Selenium testing: hard assertions and soft assertions.

Hard Assertions

Hard assertions are used when we want our test script to halt immediately if the assertion conditions do not match the expected result. If the assertion condition fails to meet the expected outcome, an assertion error will be encountered, and the test case under execution will be marked as failed.

The login situation can be used as an example of a hard assertion. A hard assert can stop the test’s execution immediately if incorrect login credentials are found. This prevents the execution of subsequent test actions because the test case can’t continue without the correct login credentials.

Methods used for hard assertions are assertEquals(), assertTrue(), assertFalse(), assertNotNull(), etc.

Soft Assertions

In soft assertions, the test script continues its execution seamlessly even if one of the assertions fails. Moreover, with soft assertions, assertion failure conditions don’t trigger any error, ensuring uninterrupted execution of test scripts as they seamlessly proceed to the next test case.

Soft assertions in Selenium can verify multiple page elements on a landing page. They allow all steps to execute and throw an error only at the end of the @Test() method.

The assertAll() method can be used for soft assertion.

Ready to set up your JUnit environment for your first test? The blog “How To Setup JUnit Environment For Your First Test” guides you through the process step-by-step.

Assert Methods In JUnit

To use JUnit assert methods, we have to import the “org.junit.jupiter.api.Assertions” class. All the JUnit assertion methods are static methods, providing a range of utility methods to assert conditions in tests. Now, we will look into different methods to assert in JUnit by examples.

If you are not familiar with JUnit, you can refer to our blog: Automated Testing with JUnit and Selenium for Browser Compatibility.

assertTrue() in JUnit

If you wish to pass the parameter value as True for a specific condition invoked in a method, you can use the assertTrue() in JUnit. You can use JUnit assertTrue() in two practical scenarios.

Syntax

  • By passing condition as a boolean parameter used to assert in JUnit with the assertTrue() method. It throws an AssertionError (without message) if the condition given in the method isn’t True.
Assert.assertTrue(boolean assertCondition);
  • By passing two parameters simultaneously in the assertTrue() method. One parameter would be an assertion error message, and the second parameter would specify the particular condition against which we need to apply our assertion method as True. It throws an AssertionError (with message) if the condition given in the method is not True.
Assert.assertTrue(String message, boolean assertCondition);

Let us understand assertTrue() in JUnit with the help of an example.

We want to verify that when users navigate to the E-Commerce TestMu AI, they are taken to the correct URL. We’ve written “assertURL()” test method to automate this verification process.

Code for assertTrue() in JUnit:

import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Test;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;


public class Main {
    static WebDriver driver = new ChromeDriver();


    @BeforeClass
    public static void openBrowser() {
        driver = new ChromeDriver();
        driver.manage().window().maximize();
    }


    @Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");


        String actualURL = driver.getCurrentUrl();
        System.out.println("URL : " + actualURL);


        String expectedURL = "https://ecommerce-playground.lambdatest.io/";


        Assert.assertTrue("URL does not match", expectedURL.equals(actualURL));
        System.out.println("Test Passed");
    }


    @AfterClass
    public static void closeBrowser() {
        driver.close();
    }
}

In the above code, we can see that we have provided two parameters in the assertTrue() method, which is an assertion error message and a boolean condition. If the condition does not match or is not true, then the assertion error will be thrown, and execution of the program will get terminated at this same line, i.e., an assertion statement itself.

So, in this scenario, assertTrue() in JUnit acts as your validation tool, confirming that the URL you expect (https://ecommerce-playground.lambdatest.io/) is indeed the URL you’ve navigated to (https://ecommerce-playground.lambdatest.io/). As both are equal, the test passes, giving you confidence in the correctness of the website’s URL.

Output:

Output:

If we do not want to provide an assertion error message, we can provide the condition as seen in the syntax mentioned above.

When running tests across different browsers, browser-specific behavior can sometimes cause assertion failures. KaneAI, a GenAI native test agent offered by TestMu AI, helps analyze these failures and provides actionable insights to resolve browser-related issues efficiently.

Automate web and mobile tests with KaneAI by TestMu AI

assertEquals()

The JUnit assertEquals() method compares the equality of the expected result with the actual result. When the expected result we provided does not match the actual result of the Selenium testing script, which we get after the action is performed, it throws an assertion error. This leads to the termination of the execution of the test script at that line itself.

The assertEquals() method in JUnit is overloaded to accommodate various data types, including byte, char, double, float, int, long, Object, and short. In addition, error messages can be included as arguments to provide context when a test fails.

Syntax:

// Comparing integers
Assertions.assertEquals(int expected, int actual)


// Comparing objects
Assertions.assertEquals(Object expected, Object actual)


// Comparing objects with an assertion error message
Assertions.assertEquals(Object expected, Object actual, String message)    

Here is a JUnit assertEquals() example to help you understand the process better.

@Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        Assertions.assertEquals("https://ecommerce-playground.lambdatest.io/", actualURL);
        System.out.println("Test Passed");
    }

In the above code, we can see that we have provided two parameters in the JUnit assertEquals() method: an expected result and an actual result. If the value of “actualURL” does not match the expected URL mentioned in the Selenium testing script, then the assertion error will be thrown, and execution of the program will get terminated at this same line, i.e., the assertion statement itself.

We can also pass an assertion error message as a parameter shown in syntax.

JUnit assertEquals() for Floating Point Assertion

When comparing floating point types (e.g., double or float), we must provide an additional parameter known as delta to avoid rounding errors.

The value for delta can be evaluated as:

Math.abs(expected – actual) = delta

If there is any marginal difference in the expected and actual values due to rounding off, those can be considered the same, and the assertion should be marked as pass. So, the delta value given by the user decides which margin value should be considered fine to pass that assertion.

Assert JUnit Example for Floating Point Assertion

@Test
    public void assertValue() {      
        double actualDoubleValue= 2.999;
        double expectedDoubleValue = 3.000;
       
        Assertions.assertEquals(expectedDoubleValue, actualDoubleValue, 0.001);
       
        System.out.println("Test Passed");            
    }

This method, “assertValue,” compares two double values: “actualDoubleValue” (initialized as 2.999) and “expectedDoubleValue” (initialized as 3.000), with a precision of 0.001. If they’re approximately equal, “Test Passed” is printed.

assertFalse()

We can make use of the assertFalse() method to verify whether a given condition is False or not.

Syntax:

Assertions.assertFalse (boolean condition)


// With an assertion error message
Assertions.assertFalse (boolean condition, String message)

Note: The assertFalse() method supports only a boolean value as a parameter.

Let us look at an assert JUnit example Selenium test script for assertFalse():

@Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");


        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);


        String expectedURL = "https://www.google.com/";


        Assertions.assertFalse(expectedURL.equals(actualURL), "URL does match");
        System.out.println("Test Passed");
    }

In the above Selenium test script, we can see that we have provided two parameters in the assertFalse() method: an assertion error message and a boolean condition. Suppose the condition does match or is not false. In that case, the assertion error will be thrown, and the program’s execution will terminate at this same line, the assertion statement itself.

If we do not want to provide an assertion error message, we can just provide a condition, as we can see in the syntax mentioned above.

assertNull()

To verify whether a passed object contains a null value, we use the assertNull() method. This method helps display an assertion error if the object does not have null values. It only supports the object data type as its parameter. In addition, error messages can be included as arguments to provide context when a test fails.

Syntax:

Assertions.assertNull(Object obj);


// With an assertion error message
Assertions.assertNull(Object obj, String msg);

Let us look at an example Selenium test script for JUnit assertNull().

@Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");
       
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
       
        String expectedURL = null;
       
        // Assertion    
        // Assertions.assertNull("Not Null",actualURL);
        // OR
        Assertions.assertNull(expectedURL, "Not Null");
 
        System.out.println("Test Passed");  
    }

In the above code, we can see that we have provided two parameters in the assertNull() method: an assertion error message and an object. If the provided object is not null, the assertion error will be thrown, and the program’s execution will terminate at this same line, the assertion statement itself.

When the “actualURL” is passed as an object, an assertion error is thrown as it is not null. Conversely, when we pass the “expectedURL,” assertion passes, indicating that the expected URL is indeed null, and “Test Passed” is printed to the console.

If we do not want to provide an assertion error message, then we can provide an object, as we can see in the syntax mentioned above.

assertNotNull()

assertNotNull() method checks if the provided object does not hold a null value. We can pass an object as a parameter in this method and get an assertion error if the object we pass does hold “NULL” values along with the assertion error message if provided.

Syntax:

Assertions.assertNotNull(Object obj);


// With an assertion error message
Assertions.assertNotNull(Object obj, String msg);

Let us look at an assert JUnit example Selenium test script for assertNotNull():

@Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");
       
        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
       
        String expectedURL = null;
       
        // Assertion    
        Assertions.assertNotNull(actualURL, "Not Null");
        // OR
        // Assertions.assertNotNull(expectedURL, "Not Null");
 
        System.out.println("Test Passed");  
    }

In the above code, we can see that we have provided two parameters in the assertNotNull() method: an assertion error message and an object. If the provided object is null, only the assertion error will be thrown, and the program’s execution will get terminated at this same line, i.e., the assertion statement itself.

When the “actualURL” is passed as an object, then assertion passes, indicating that the expected URL is not null, and “Test Passed” is printed to the console. When we pass the “expectedURL”, an assertion error is thrown as it is null.

If we do not want to provide an assertion error message, we can just provide an object, as seen in the syntax mentioned above.

assertSame()

While performing Selenium testing, you may often encounter a scenario where you need to compare two different objects passed as parameters in a method to evaluate whether they refer to the same object or not. This is where you can use JUnit assertSame(). An assertion error is displayed if the two objects don’t refer to the same object. Also, we will receive an assertion error message if the message is provided as shown in the syntax below.

Syntax:

Assertions.assertSame (Object expected, Object actual)


// With an assertion error message
Assertions.assertSame (Object expected, Object actual, String message)

Note: It only supports the object data type as its parameter.

Let us look at an assert JUnit example Selenium test script for assertSame():

@Test
    public void assertString() {      
        String actual = "LambdaTest";
        String expected = actual;
        String other = "JUnit";
       
        // Assertion
        Assertions.assertSame(expected, actual, "Strings not same");
       
        // OR
        // Assertions.assertSame(expected, other, "Strings not same");
       
        System.out.println("Test Passed");  
    }

This “assertString” method is a JUnit test case that aims to verify the equality of two string objects. Initially, both “expected” and “actual” strings are assigned the value “TestMu AI.” The “Assert.assertSame()” method is then employed to assert that both strings reference the same object in memory, ensuring that they are identical instances. If the assertion succeeds, indicating that both strings are references to the same object, the message “Test Passed” is printed to the console.

When “expected” and “other” strings are passed as objects, the assertion statement checks whether the references of expected and others point to the same object in memory. Since “TestMu AI” and “JUnit” are different string literals, they are stored as separate objects in memory. Therefore, the assertion fails, the execution of the method halts, and “Test Passed” is not printed to the console.

If we do not want to provide an assertion error message, we can just provide an object, as seen in the syntax mentioned above.

assertNotSame()

assertNotSame() method verifies that if the two objects we passed as parameters are not equal. If both objects have the same references, an Assertion Error will be thrown with the message we provided (if any).

One more thing to observe in this method is that it compares references to objects and not the values of those objects.

Syntax:

Assertions.assertNotSame (Object unexpected, Object actual)


// With an assertion error message
Assertions.assertNotSame (Object unexpected, Object actual, String message)

Note: It only supports the object data type as its parameter.

Let us look at an assert JUnit example Selenium test script for assertNotSame():

@Test
    public void assertString() {      
        String actual = "LambdaTest";
        String expected = actual;
        String other = "JUnit";
       
        // Assertion
        Assertions.assertNotSame(expected, actual, "Strings are not same");
       
        // OR
        // Assertions.assertNotSame(expected, other, "Strings are not same");
       
        System.out.println("Test Passed");  
    }

This “assertString” method is a JUnit test case that aims to verify the equality of two string objects. Initially, both “expected” and “actual” strings are assigned the value “TestMu AI”. The “Assert.assertNotSame()” method verifies that the references of expected and actual do not point to the same object in memory. Since both expected and actual are initialized with the exact string literal “TestMu AI,” they are likely referencing the same object in memory. Thus, the assertion is expected to fail. Upon failure, the execution halts, and “Test Passed” is not printed to the console.

When “expected” and “other” strings are passed as objects, the assertion statement checks whether the references of expected and other do not point to the same object in memory. Since “TestMu AI” and “JUnit” are different string literals, they will likely be stored as separate objects in memory. Therefore, the assertion is expected to pass. Upon successful assertion, “Test Passed” is printed to the console, indicating that the test has successfully verified that “expected” and “other” are indeed referencing different objects in memory.

If we do not want an assertion error message, we can just provide an object, as seen in the above mentioned syntax.

assertArrayEquals()

assertArrayEquals() method verifies that the two object arrays we passed as parameters are equal. If both the object arrays have null values, then they will be considered equal.

The “assertArrayEquals()” method in JUnit is versatile, as it’s overloaded to accommodate various data types, including boolean, byte, char, double, float, int, long, Object, and short. This allows efficient comparison of arrays of different primitive types and objects within test cases. This method will also throw an Assertion Error with the message provided if both the object arrays we passed as parameters in the method are not considered equal.

Syntax

// For integer arrays
Assertions.assertArrayEquals (int expected, int actual)


// For object arrays
Assertions.assertArrayEquals (Object expected, Object actual)


// With an assertion error message
Assertions.assertArrayEquals (int expected, int actual, String message)  

Let us look at an assert JUnit example Selenium test script for assertArrayEquals():

@Test
    public void asserArrays() {      
        // Create two arrays to compare
        int[] expectedArray = {1, 2, 3, 4};
        int[] actualArray = {1, 2, 3, 4};


        // Assert that the arrays are equal  
        Assertions.assertArrayEquals(expectedArray, actualArray, "Arrays are not equal");
        System.out.println("Test Passed");  
    }

This JUnit test method, assertArrays(), verifies the equality of two arrays, expectedArray and actualArray, using the assertArrayEquals() method. If the arrays are equal, the test passes and prints “Test Passed”. If they are not equal, the test fails with the assertion error message “Arrays are not equal.”

If we do not want to provide an assertion error message, we can just provide an object, as we can see in the syntax mentioned above.

assertAll()

The newly added method assertAll() will be executed to check all the assertions as grouped assertions. It has an optional heading parameter that allows to recognize a group of assertions with that method assertAll(). At the time of failure, the assertion error message shows detailed information about each and every field assertion used in that group.

Syntax:

Assertions.assertAll(executables...);

Here, executables represent one or more instances of Executable interface, typically lambda expressions or method references, that encapsulate the assertions to be performed. The “assertAll()” method verifies all assertions provided by the executables, and if any of them fail, it aggregates the failures and reports them together.

Let’s look at an assert JUnit example for assertAll() with the grouped assertion:

@Test
    public void assertURL() {
        driver.get("https://ecommerce-playground.lambdatest.io/");


        String actualURL = driver.getCurrentUrl();
        System.out.println(actualURL);
        String expectedURL="https://ecommerce-playground.lambdatest.io/";
           
        String actualTitle =  driver.getTitle();
        System.out.println(actualTitle);
        String expectedTitle = "Your Store";
       
        Assertions.assertAll(
                () -> Assert.assertEquals(expectedURL, actualURL),
                () -> Assert.assertEquals(expectedTitle, actualTitle)
                );
       
        System.out.println("Test Passed");
    }

In the “assertURL()” test method, the Selenium WebDriver navigates to the TestMu AI website and captures the current URL and page title. Using assertAll(), it groups together two assertEquals() assertions, comparing the expected and actual URL and title. If both comparisons hold true, indicating that the URL and title match expectations, the test pass and “Test Passed” is printed.

assertIterableEquals()

The assertIterableEquals() method verifies whether two iterables are equal. It compares the elements of the iterables sequentially, ensuring they have the same size and contain equivalent elements in the same order. This method is particularly useful for comparing collections like lists, sets, and queues, providing a concise and efficient way to validate their contents in test cases.

Syntax:

Assertions.assertIterableEquals(Iterable<?> expected, Iterable<?> actual)


// With assertion error message
Assertions.assertIterableEquals(Iterable<?> expected, Iterable<?> actual, String message)

Let’s look at an assert JUnit example for assertIterableEquals() method:

@Test
    public void assertIterable() {
        List<Integer> firstList = Arrays.asList(1, 2, 3);
        List<Integer> secondList = Arrays.asList(1, 2, 3);
        List<Integer> thirdList = Arrays.asList(3, 1, 2);
       
        Assertions.assertIterableEquals(firstList, secondList, "Not Same List");
        // OR
        // Assertions.assertIterableEquals(firstList, thirdList, "Not Same List");


        System.out.println("Test passed");
    }

When the elements passed are firstList and secondList, the test passes, indicating that the lists are equal. When the elements passed are firstList and thirdList, the test fails, indicating a discrepancy between the elements or their order.

assertTimeout()

The assertTimeout() method in JUnit is used to ensure that the execution of the system under test is complete within a specified timeframe. It accepts various parameters, such as a duration object and an executable, allowing flexibility in defining the execution boundaries. This method empowers testers to enforce time constraints on test executions, ensuring timely and reliable validation of system behavior.

Additionally, it supports the inclusion of error messages as arguments to provide context in case of test failure, aiding in diagnosing issues when the timeout condition is breached.

Syntax:

Assertions.assertTimeout (Duration timeout, Executable executable)


// With an assertion error message
Assertions.assertTimeout (Duration timeout, Executable executable, String message)

Let’s look at an assert JUnit example for assertTimeout() method:

@Test
    public void testTimeout() {
        // Assert that an operation completes within 1 minute
        Assertions.assertTimeout(Duration.ofMinutes(1), () -> {
            // Simulate a time-consuming operation (
            performTimeConsumingOperation();
        });


        // Assert that an operation completes within 100 milliseconds
        // Assertions.assertTimeout(Duration.ofMillis(100), () -> {
            // Simulate a time-consuming operation that exceeds the timeout
            //Thread.sleep(200);
        //});
       
        System.out.println("Test passed");
    }


    // Method to simulate a time-consuming operation
    public void performTimeConsumingOperation() {
        // Simulate a time-consuming operation
        try {
            Thread.sleep(500); // Simulate a 500-millisecond operation
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

The first assertion specifies a timeout duration of one minute. Within this duration, the performTimeConsumingOperation() method is called, which simulates a time-consuming operation, and if this operation completes within the specified timeout, the test passes; otherwise, it fails, indicating that the operation took longer than expected.

The second assertion defines a shorter timeout of 100 milliseconds. Here, a time-consuming operation that exceeds the timeout duration is attempted by introducing a delay of 200 milliseconds. As this operation surpasses the specified timeout, the test fails, highlighting the effective enforcement of time constraints in test executions.

assertTimeoutPreemptively()

The assertTimeoutPreemptively() method in JUnit 5 is similar to assertTimeout(). Still, with one key difference, i.e., it forcefully interrupts the execution of the test if it exceeds the specified timeout duration. This preemptive interruption ensures that the test does not continue executing beyond the defined time limit, even if the code under test does not respond to interruption signals. It supports the duration object and an executable.

Syntax:

Assertions.assertTimeoutPreemptively(Duration timeout, Executable executable)


// With assertion error message
Assertions.assertTimeout Preemptively(Duration timeout, Executable executable, String message)

Let’s look at an assert JUnit example for assertTimeoutPreemptively() method:

<em>@Test</em>
	void testTimeoutPreemptively() {
       		<em>Assertions.assertTimeoutPreemptively</em>(Duration.ofSeconds(1), () -> {
           		// Simulate a time-consuming operation 
          		 while (true) {
              	 // Infinite loop to simulate a time-consuming operation
           			}
      	 	});
   	}

In this example, as the code within the lambda expression does not execute in one second and the assertTimeoutPreemptively() will forcefully terminate the test, preventing it from continuing indefinitely.

fail()

The fail() method in JUnit is a way to mark a test as failed programmatically. It allows us to specify a message indicating the reason for the failure. This approach allows for precise error reporting and aids in diagnosing issues encountered during test execution. It supports a string and throwable values as parameters.

Syntax:

// With error message


Assertions.fail(String message)


// With error messaage and cause


Assertions.fail(String message, Throwable cause)

Let’s look at an assert JUnit example for fail() method:

@Test


    public void testFunction() {


        // Perform some checks


        try {


            // Simulate an error condition


            throw new RuntimeException("Error occurred during test execution");


        } catch (RuntimeException error) {


            // If an error occurs, fail the test with a custom message and the associated exception


            Assertions.fail("Test failed due to an error", error);


        }


    }

In this JUnit test method testFunction(), we simulate an error condition by intentionally throwing a RuntimeException with a specific error message (“Error occurred during test execution”). Within the catch block, we call fail() method to explicitly mark the test as failed, providing a custom error message and the associated exception.

assertThrows()

The assertThrows() is another newly added method in JUnit 5 to replace the ExpectedException Rule from JUnit 4. Now, all assertions can be made against the returned instance of a class Throwable, making the test scripts more readable. As executables, we can use lambdas or method references.

Syntax:

Assertions.assertThrows (Class<T> expectedType, Executable executable)


// With assertion error message


Assertions.assertThrows (Class<T> expectedType, Executable executable, String message)

Note: It supports only exception classes and executable as parameters.

Let’s look at an assert JUnit example for assertThrows() method:

@Test


    public void testDivideByZero() {


        // Define a lambda expression to call the method that you expect to throw an exception


        Assertions.assertThrows(ArithmeticException.class, () -> divide(10, 0));


        System.out.println("Test Passed");


    }


    // Method that performs division


    public double divide(int dividend, int divisor) {


        if (divisor == 0) {


            throw new ArithmeticException("Cannot divide by zero");


        }


        return dividend / divisor;


    }

In the testDivideByZero() method, assertThrows() method is used to verify that invoking the divide() method with arguments 10 and 0 results in an ArithmeticException being thrown, as expected. The test passes if the exception is thrown, indicating an attempt to divide by zero. Additionally, “Test Passed” is printed on the console, affirming the successful completion of the test.

This JUnit Tutorial for beginners and professionals will help you learn JUnit Assertions in Selenium.

Youtube thumbnail
Test your website on the TestMu AI real device cloud

Third-Party Assertions In JUnit

JUnit Jupiter provides sufficient assertion facilities for most testing scenarios. Still, some scenarios require additional functionalities, such as matchers, that are not provided by JUnit Jupiter.

For such scenarios, the JUnit team recommends using third-party assertion libraries like Hamcrest, AssertJ, Truth, etc. Users can use these third-party libraries whenever necessary.

For an assert JUnit example, we can use a combination of matchers and a fluent API to make assertions more descriptive and readable.

JUnit Jupiter’s (JUnit 5) org.junit.jupiter.api.Assertions class does not provide the method assertThat() that was available with the org.junit.Assert class in JUnit 4, which accepts a Hamcrest Matcher. That way, you can leverage the built-in support for matchers offered by third-party assertion libraries.

Assert JUnit Example for Selenium Testing using Third-Party assertions:

@Test


    public void testPageTitleContainsSubstring() {


        // Navigate to the web page


        driver.get("https://ecommerce-playground.lambdatest.io/");


        // Get the title of the web page


        String title = driver.getTitle();


        // Verify that the title contains the specified substring using Hamcrest matcher


        assertThat(title, containsString("Store"));


       


        System.out.println("Test passed");


    }

In the testPageTitleContainsSubstring() test method, the Selenium WebDriver navigates to the TestMu AI website. After retrieving the web page’s title, it verifies that the title contains the specified substring “Store” using the Hamcrest matcher containsString() method. If the substring is found in the title, the test passes. Additionally, “Test passed” is printed on the console, indicating the successful completion of the test.

You can find the GitHub repository for all the above codes at this GitHub repo.

How Do AI Tools Help Write and Debug JUnit Assertions?

AI coding agents such as GitHub Copilot and Claude Code can draft a JUnit assert call from a test method, and dedicated tools like Diffblue Cover can generate whole JUnit assertions automatically.

  • Assertion drafting from context: GitHub Copilot and Claude Code can read a Selenium test method and suggest the matching assert call, for example choosing assertEquals() over assertTrue() when the comparison involves two typed values instead of a single boolean.
  • Automated assertion generation: Diffblue Cover analyzes existing Java code and writes complete JUnit test methods with assertions attached, without a human writing the test first, though the generated assertions still need a review for business intent.
  • Missing-assertion detection: AI-assisted code review can flag a JUnit test method that runs Selenium steps but never calls an assert method, a gap known as an assertion-free test that always reports as passing even when the page under test is broken.
  • Expected-value limitation: an AI agent can draft the assert call and pick the right method, but it cannot decide the correct expected value on its own, so a tester still has to confirm what the test should verify.

Bonus Resource

Hence, a professional certification in JUnit is worth considering to increase your credibility in the talent pool. You can also check JUnit certification from TestMu AI. TestMu AI is an AI-Native test orchestration and execution platform that lets you run manual and automated tests at scale on over 3000 real devices, browsers, and OS combinations.

This JUnit Certification establishes testing standards for those who wish to advance their careers in Selenium automation testing with JUnit.

Austin Siewert

Austin Siewert

Co-Founder, Steadfast Systems

Discovered @TestMu AI yesterday. Best browser testing tool I've found for my use case. Great pricing model for the limited testing I do 👏

3M+ Devs and QAs rely on TestMu AI

Deliver immersive digital experiences with Next-Generation Mobile Apps and Cross Browser Testing Cloud

Here’s a short glimpse of the JUnit certification from TestMu AI:

Youtube thumbnail

You can also explore more videos from the TestMu AI YouTube Channel on Assertions In pytest, Assertions in Selenium, and Assertions in TestNG to enhance your testing experience!

Conclusion

Assertions are indispensable if you are performing Selenium. They help us determine whether a test case has passed or failed by evaluating the parameters passed into objects through our Selenium testing scripts. If you wish to manage automation logs neatly and organize them, assertions can do wonders for you.

So far, we have learned various methods to assert in JUnit, like assertTrue() in Junit, assertThrows() in Junit, etc., with examples. We also dwelled upon the difference between JUnit5 and JUnit4 with respect to assertions in JUnit. We also covered the newly introduced assertions and third-party assertions in JUnit.

JUnit Assertions

JUnit assertions allow developers to validate expected outcomes and behaviors within their Java code. These assertions ensure the correctness of the application's functionality during testing. With JUnit Assertions, developers can construct dependable test suites, enhancing the reliability and effectiveness of their testing processes.

To learn more about JUnit Assertions, follow the complete video tutorial guide, get valuable insights, and learn when and how to use assertions.

Youtube thumbnail

JUnit 4 Assertions

Assertions are a core element in Selenium automation. They verify that the actual outcome of a test matches the expected result.

Assertions sit after actions in the code, comparing actual results against expected ones. A match passes the test; a mismatch fails the assertion and marks the test failed.

JUnit provides a set of built-in assertion methods that handle this validation in Java-based test scripts.

For better understanding, let us look into the JUnit 4 Assertions with examples below.

  • assertEquals(): Compares expected and actual results. If they do not match, an assertion error triggers and the script stops at that line.
  • The syntax for assertEquals()is as follows:


    Assert.assertEquals(String expected, String actual);
    Assert.assertEquals(String message, String expected, String actual);

    The assertFalse() method takes a parameter value set to true for a condition within a method. The JUnit assertTrue() function serves two primary purposes:

    • Providing a condition as a parameter for assertion application.
    • If a method fails to meet the specified condition, it triggers an AssertionError without a message.

    These methods contribute to effective result validation and error handling in automated testing scenarios.


  • assertArrayEquals(): Checks whether two object arrays are equal. Two null arrays count as equal; unequal content throws an AssertionError.
  • The syntax for assertArrayEquals() is as follows:


    Assert.assertArrayEquals(Object[] expected, Object[] actual);
    Assert.assertArrayEquals(String message, Object[] expected, Object[] actual);
    );

    This method proves useful for comparing arrays and ensuring that their content matches the expected values, supporting reliable assertion handling in automated testing scenarios.


  • assertNull() : Verifies that an object is null. A non-null object triggers an assertion error. A variant accepts a custom message.
  • The syntax for assertNull() is as follows:


    Assert.assertNull(Object obj);
    Assert.assertNull(String msg, Object obj);
    

  • assertNotNull() : Verifies that an object is not null. A null object triggers an assertion error. A variant accepts a custom message.
  • The syntax for assertNotNull() is as follows:


    Assert.assertNotNull(Object obj);
    Assert.assertNotNull(String msg, Object obj);

    These methods are valuable for effective null value checking and assertion handling in automated testing scenarios.


  • assertSame() : Checks whether two objects refer to the same instance. Different references trigger an assertion error, optionally with a custom message.
  • The syntax for assertSame() is as follows:


    Assert.assertSame(Object expected, Object actual);
    Assert.assertSame(String message, Object expected, Object actual);
    

  • assertNotSame(): Checks that two objects do not share a reference. Identical references throw an AssertionError. It compares references, not values.
  • The syntax for assertNotSame() is as follows:


    Assert.assertNotSame(Object expected, Object actual);
    Assert.assertNotSame(String message, Object expected, Object actual);

  • assertTrue(): In JUnit, the assertTrue() function is utilized to assert that a given condition is true. This function has two primary uses:
    • A condition is provided as a parameter for applying the assertion. If the method fails to satisfy this condition, an AssertionError is thrown without a specific message.

    The syntax for assertTrue() is as follows:


    Assert.assertTrue(boolean condition);
    • Additionally, the assertTrue() function accepts two parameters. The first parameter specifies the assertion error message, and the second parameter defines the condition against which assertTrue() is applied. If the given condition in the method is false, it throws an AssertionError with the provided message.

    The syntax for assertTrue() that accepts two parameters is as follows:


    Assert.assertTrue(String message, boolean condition);
    

  • assertFalse() : In contrast, the assertFalse() function in JUnit is employed to assert that a given condition is false. Similar to assertTrue(), it has two primary uses:
    • A condition is passed as a parameter. If the method fails to satisfy it, an AssertionError is thrown without a message.

    The syntax for assertFalse() is as follows:


    Assert.assertFalse(boolean condition);
    

    • The assertFalse() function also accepts two parameters. The first parameter specifies the assertion error message, and the second parameter defines the condition against which assertFalse() is applied. If the given condition in the method is not false, it throws an AssertionError with the provided message.

    The syntax for assertFalse() that accepts two parameters is as follows:


    Assert.assertFalse(String message, boolean condition);

    These functions handle assertions in automated testing scenarios, allowing for verification of conditions based on true or false outcomes.


  • fail() : Forces a test to fail by throwing an AssertionFailedError. Useful for verifying a specific exception or marking an unfinished test.
  • The syntax for fail() is as follows:


    Assert.fail();
    

    The fail() method takes no parameters and triggers an AssertionFailedError immediately. Deliberately failing a test sounds counterintuitive, but it is useful during development and debugging.


  • assertThat() : The assertThat() assertion in JUnit 4 is the only one with a reverse order of parameters compared to other assertions. In this assertion, the syntax includes an optional failure message, followed by the actual value and a Matcher object.
  • The syntax for assertThat() is as follows:


    Assert.assertThat(String message, T actual, Matcher<? super T> matcher);
    Assert.assertThat(T actual, Matcher<? super T> matcher);
    
    • The first syntax allows the inclusion of an optional failure message, the actual value being tested, and a Matcher object that defines the expected conditions.
    • The second syntax omits the failure message and directly accepts the actual value and the Matcher object.

    The assertThat() assertion enables more expressive and readable tests using Matcher objects defining success conditions.

JUnit 5 Assertions

JUnit 5 has retained many assertion methods from JUnit 4 and introduced several new ones that build on Java 8 support. In this version, assertions apply to all primitive types, objects, and arrays, whether they consist of primitives or objects.

A notable change is the reordering of parameters in the assertions, placing the output message parameter as the last. Java 8 support allows the output message to be a Supplier, facilitating lazy evaluation.

Let's look closer at the assertions with equivalents in JUnit 4:

  • JUnit 5 has maintained existing assertion methods from JUnit 4.
  • New methods build on Java 8 support for enhanced functionality.
  • Assertions apply to primitive types, objects, and various types of arrays.
  • The order of parameters in assertions has been changed, with the output message now positioned as the last parameter.
  • The use of a Supplier for the output message enables lazy evaluation.

These updates in JUnit 5 enhance the flexibility and readability of assertions in test cases. Let us look at some JUnit 5 Asserestion below with examples for better understanding.

  • assertIterableEquals() : Verifies that two iterables are deeply equal, with identical elements in the same order. Types need not match.
  • The syntax for assertIterableEquals() is as follows:


    assertIterableEquals(Iterable<?> expected, Iterable<?> actual);
    assertIterableEquals(String message, Iterable<?> expected, Iterable<?> actual);

    Example

    Here iterableEqualsPositive() asserts across two iterables holding the same elements in the same order. The types differ: one is an ArrayList, the other a LinkedList.


    @Test
    void iterableEqualsPositive() {
    Iterable<String> iterat1 = new ArrayList<>(asList("Java", "Junit", "Test"));
    Iterable<String> iterat2 = new LinkedList<>(asList("Java", "Junit", "Test"));
    
    assertIterableEquals(iterat1, iterat2);
    }
    

    In this example, the assertion passes successfully as the sequence and number of elements in both iterables are identical, fulfilling the criteria for deep equality. This flexibility in handling iterables of different types enhances the utility of assertIterableEquals() in various testing scenarios.


  • assertLinesMatch() : The assertLinesMatch() assertion in JUnit 5 is used to verify that the expected list of Strings matches the actual list of Strings. Unlike assertions primarily using String.equals(Object), this method uses a staged matching algorithm.
  • Here is how the algorithm works for each pair of expected and actual lines:

    • Check if expected.equals(actual); if true, continue with the next pair.
    • If not, treat expected as a regular expression and check using String.matches(String); if true, continue with the next pair.
    • If neither condition is met, check whether expected is a fast-forward marker. If so, fast-forward the actual lines and repeat.

    The syntax for assertLinesMatch() is as follows:


    assertLinesMatch(List<String> expected, List<String> actual);

    Example

    In the provided example, the assertLinesMatch assertion is demonstrated. The expected list contains a regular expression that matches the elements of the actual list.


    @Test
    void linesMatchExample() {
    List<String> expected = Arrays.asList("apple", "banana", ".*");
    List<String> actual = Arrays.asList("apple", "banana", "orange");
    
    
    assertLinesMatch(expected, actual);
    }

    The assertion passes because the regular expression in the expected list matches the corresponding elements in the actual list. Staged matching allows several comparison scenarios across string lists.


  • assertThrows() : Asserts that an executable, such as a lambda or method reference, throws a specified exception type.
  • The syntax for assertThrows() in JUnit 5 is as follows:


    assertThrows(Class<? extends Throwable> expectedType, Executable executable);

    Example

    In the following example, the assertion is used to test if the length of a null string (arr) throws a NullPointerException.


    @Test
    void exceptionTestingPositive() {
    String arr = null;
    Exception exception = assertThrows(NullPointerException.class, () -> arr.length());
    assertEquals(null, exception.getMessage());
    }
    
    

  • assertTimeout() : Validates that a supplied executable completes within a specified timeout, confirming an operation finishes inside a given timeframe.
  • The syntax for assertTimeout() in JUnit 5 is as follows:


    assertTimeout(Duration timeout, Executable executable);

    Example

    In the following example, assertTimeout() is set to 2 seconds, indicating that the assertion should be completed within this time frame. The test scenario involves waiting for 1 second and then performing the assertion.


    @Test
    void assertTimeoutPositive() {
    int a = 4;
    int b = 5;
    
    
    assertTimeout(
    ofSeconds(2),
    () -> {
    // code that should complete within 2 seconds
    Thread.sleep(1000);
    }
    );
    
    
    assertEquals(9, (a + b));
    }
    

  • assertTimeoutPreemptively() : Like assertTimeout(), but runs the executable in a separate thread and aborts it when the timeout passes.
  • The syntax for assertTimeoutPreemptively() in JUnit 5 is as follows:


    assertTimeoutPreemptively(Duration timeout, Executable executable);

    Example

    In the provided JUnit 5 test method, assertPreemptiveTimeoutNegative(), the objective is to demonstrate the use of assertTimeoutPreemptively() by intentionally causing a test failure due to a timeout.


    @Test
    void assertPreemptiveTimeoutNegative() {
    int a = 4;
    int b= 5;
    assertTimeoutPreemptively(
    ofSeconds(2),
    () -> {
    // code that requires less then 2 seconds to execute
    Thread.sleep(5000);
    assertEquals(9, (a + b));
    }
    );
    }
    

    The key difference is that assertTimeoutPreemptively() runs the executable in a separate thread and aborts it once the timeout passes. assertTimeout() lets it keep running, which can affect later code.

Note

Note: JUnit 6 keeps the same Jupiter API, so the assertions above compile unchanged after you upgrade.

Author

...

Hari Sapna Nair

Blogs: 8

  • Twitter
  • Linkedin

Hari Sapna Nair is a Community Contributor with experience spanning software development, technical writing, and open-source collaboration. A former Technical Content Writer at TestMu AI, she has authored guides and tutorials on Selenium, testing, microservices, and emerging technologies. Sapna has contributed 60+ technical blogs for platforms like Coding Ninjas and has been an active open-source contributor in programs such as GirlScript Summer of Code and HakinCodes, securing top contributor ranks. A GHC Scholar and an engineer turned management student at IIM Indore.

Frequently asked questions

Did you find this page helpful?

More Related Blogs

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests