Mastering Selenium Testing: JUnit Asserts With Examples

Hari Sapna Nair

Posted On: March 22, 2024

view count230993 Views

Read time23 Min Read

Automation testing helps to ease the life of software testers by allowing them to automate their repetitive tasks, and open-source test automation frameworks like Selenium have enabled users to automate web testing experience at scale. However, what good is automation testing if you cannot verify whether a test case has passed or failed?

This is where assertions come into the picture. They allow you to keep track of the number of test failures or successes encountered after executing your automation script for Selenium testing. Let’s look at examples to learn how to assert in JUnit and the different assert methods used in JUnit.

We will start with a basic introduction to assertions in JUnit and then cover the various assert methods in JUnit, focusing on the assertTrue() method. If you are preparing for an interview you can learn more through Selenium interview questions.

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.

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.
  • 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.

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

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

Code for assertTrue() in JUnit:

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, offered by LambdaTest, helps analyze these failures and provides actionable insights to resolve browser-related issues efficiently.

By optimizing Selenium test execution on Chrome, Firefox, and Edge, KaneAI reduces the time spent troubleshooting, ensuring smoother test runs.

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:

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

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

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:

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():

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:

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

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 holdNULL values along with the assertion error message if provided.

Syntax:

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

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:

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

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

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 “LambdaTest.” 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 “LambdaTest” 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:

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

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

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 “LambdaTest”. 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 “LambdaTest,” 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 “LambdaTest” 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

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

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:

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:

In the “assertURL()” test method, the Selenium WebDriver navigates to the LambdaTest 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:

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

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:

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

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:

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

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:

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

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:

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

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

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.

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:

In the testPageTitleContainsSubstring() test method, the Selenium WebDriver navigates to the LambdaTest 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.

Bonus Resource

According to Statista Research Department’s stats published on 21 February 2024, in 2023, JUnit was the primary technology used among test frameworks and tools, with 34% of respondents worldwide reporting the same. This comes after a small dip in 2022, when it was only 31%.

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 LambdaTest. LambdaTest is an AI-powered 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.

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

You can also subscribe to the LambdaTest YouTube Channel for more videos 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.

Frequently Asked Questions (FAQs)

What is assert in JUnit testing?

For writing assertions in JUnit tests, you must use the JUnit Assert class. It offers a number of assertions to check for things like object nullness, value equality, and boolean variable values. Developers can confirm expected results and increase the dependability of their tests by utilizing the JUnit Assert class.’

When should we use assertTrue() in JUnit?

We should use assertTrue() in JUnit when we want to validate that a certain condition or expression is true during testing. It’s particularly useful for verifying expected outcomes or behaviors in your code.

Why assert is used in JUnit?

Assertions play a key role in test case development by comparing the expected and actual outputs. In JUnit, the assert class offers a range of assertion methods to facilitate this comparison and determine test case success or failure.

What is assert () in Java?

In Java, the assert() statement tests conditions during program execution, triggering an exception if the condition is false. It helps identify unexpected behavior or invalid states in the code for debugging purposes.

What happens if assertTrue() in JUnit fails?

If assertTrue() in JUnit fails, it indicates that the expected condition was not met during testing. The test case will be marked as failed, and any subsequent assertions in the test method will not be executed.

Author Profile Author Profile Author Profile

Author’s Profile

Hari Sapna Nair

Sapna works as a Content Writer at LambdaTest. An avid reader and passionate developer, she embraces the role of a tech blogger who loves to share her wealth of knowledge. Firmly believing in personal growth through uplifting others, she has chosen blogging as her medium for this purpose. Always eager to learn more and connect with new people, she remains ready to explore new horizons and engage with diverse audience.

Blogs: 8



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free