Understanding JUnit assertions for Selenium Testing with Examples
On This Page What are Assertions in Selenium Testing?February 11, 2026 · 14 min read · Tool Comparison
JUnit assertions are essential for validating test outcomes in Selenium mechanization. They facilitate reassert that your application behaves as ask during UI tests. What are JUnit Assertions? JUnit assertions are methods used to control that a specific condition is true during test performance. If the precondition miscarry, the test is marked as failed, helping place bugs betimes in the development rhythm. Mutual Assertions in JUnit 5 JUnit 5 provides a comprehensive set of statement to validate different weather in your tests. This article explains how to use these JUnit 5 assertions effectively in Selenium tests, with practical examples to fortify your test mechanization scheme. Assertions in validate that your web application behaves as expected during test execution. While Selenium grip browser automation (like clicking buttons or filling forms), assertions arrive from test frameworks like or and control outcomes, such as page titles, element values, or the presence of UI components. By adding averment to your Selenium exam, you can automatically check whether: If an assertion fails, the tryout Newmarket and is marked as neglect, helping catch bug early and faithfully. There are two chief types of JUnit assert methods. In hard assert, the program execution stops as soon as an exception occurs and thereby skipping all the next steps in the test method. It throw an Assertion error and marks the test example as failed though all the steps in the test method were not accomplish. After the assert fails, the current exam is skipped and the next@Testis executed. Example: Hard assert can be used in login scenarios, where we would like the execution to stop if the login credentials are not valid. In some cases, we need the test execution to keep even when there is any exception encountered. Soft Asserts do not throw an Assertion erroneousness if there is any exception and rather tape the failure. Later, it collects all the statement throughout the@Testmethod and shed all the exceptions get during the process with theassertAll () method. Example: Soft assert can be expend to verify multiple page elements of any landing page, where we would like all the steps to be executed and to throw an error entirely at the concluding line of the@Test method. Also Read: JUnit 5 introduces a more flexible and modern testing architecture than JUnit 4. It supports new programming paradigms and provides better extensibility for advanced examination demand. Here are the key benefits: Read More: Read More: Assuming Selenium Java and WebDriverManager JARs are already included, the future measure is to add the JUnit 5 library and its. Add the following colony inside the & lt; dependencies & gt; tag in the pom.xml file of the Maven task you are utilize. Also, add JUnit5 library by correct clicking on the Maven undertaking and selecting - & gt;“ Build Path ”>> “ Configure Build Path ” >> “ Add Library ”>> JUnit. Click “Next”, Select “JUnit5” from the “ JUnit Library variant ”dropdown and click on“Finish”. Finally click“ Apply and Close ”to relieve the configuration. To use JUnit assert methods, import org.junit.jupiter.api.Assertions class. All JUnit Jupiter Assertions are static methods. As per the official document, “ Assertions is a collection of usefulness methods that support asserting conditions in tests. ” 1. assertEquals () Use Assertions.assertEquals ()method, if you ask to assert that any given two values are adequate. assertEquals ()is an overladen method for different information types such asbyte, char, double, float, int, long, Object, short. It also indorse error messages to be passed as an arguing in case of test failure. Syntax: Program: In the first assertion, we are expecting “0123-23456” and the actual value is “0123-456-789”. So, the statement will betray. In the 3rd assertion, we are expecting “JUnit5”, and actual value is “JUnit4”, so the assert will fail with the message passed. In case of failure,AssertionFailedErrorexception will be throw in the undermentioned manner: 2. assertNotEquals () UseAssertions.assertNotEquals ()method, if you need to assert that given any two values are not adequate. assertNotEquals ()support only Object data eccentric as argument. It also supports erroneousness messages to be legislate as an argument in case of test failure. Syntax: Program: In case of failure,AssertionFailedErrorexception will be thrown in the following mode: 3. assertArrayEquals () Use Assertions.assertArrayEquals ()method, if you ask to avow that afford any two arrays are equal. assertArrayEquals ()is an overloaded method for different data types such asboolean[], byte[], char[], double[], float[], int[], long[], Object[], short[]. It also supports error messages to be legislate as an argument in case of test failure. Syntax: Program: The assert will fail as element order is different. In cause of failure,AssertionFailedErrorexception will be thrown in the following manner: 4. assertNull () Use Assertions.assertNull ()method, if you need to assert that given any value is void. assertNull ()supports simply Object data type as parameter. It also support fault message to be legislate as an argument in case of test failure. Syntax: Program: For autonomous testing across multiple user personas, check out SUSATest — it explores your app like 10 different real users. The second assert will fail as we are pass ingredient thread value which is not null In case of failure,AssertionFailedErrorexception will be thrown in the following manner: 5. assertNotNull () Use Assertions.assertNotNull ()method, if you demand to assert that give any value is not void. assertNotNull ()supports solely Object data type as argument. It likewise supports error messages to be passed as an argument in causa of test failure. Syntax: Program: The 2d assert will neglect as we are explicitly passing void value. In lawsuit of failure,AssertionFailedErrorexception will be shed. 6. assertSame () Use Assertions.assertSame ()method, if you need to avow that given any two value name to the same objective. assertSame ()supports merely Object data type as parameter. It also supports error content to be passed as an argument in case of test failure. Syntax: Program: First assert will pass as transcript ands1refer to the same aim Second assert will fail ass1 and s2refer to the different object In case of failure,AssertionFailedErrorelision will be thrown in the following manner: 7. assertNotSame () Use Assertions.assertNotSame ()method, if you ask to assert that give any two values do not pertain to the same aim. assertNotSame ()support only Object information type as parameter. It also indorse error messages to be passed as an argument in case of test failure. Syntax: Program: First assertwill miscarry ass1and transcript refer to the same target Second assertwill pass ass1 and s2refer to the different object In case of failure,AssertionFailedErrorexception will be thrown in the following manner: 8. assertTrue () Use Assertions.assertTrue ()method, if you need to assert that the supplied condition istrue. assertTrue ()support only boolean value as parameter. It too endorse error content to be pass as an disceptation in lawsuit of test failure. Syntax: Program: Second assert will fail as5<0return mistaken In event of failure,AssertionFailedErrorexception will be cast in the undermentioned manner: 9. assertFalse () Use Assertions.assertFalse ()method, if you take to assert that the supplied stipulation is mistaken. assertFalse ()support only boolean value as parameter. It likewise supports fault messages to be surpass as an argument in case of examination failure. Syntax: Program: Third assertwill fail as element is displayed on webpage which is true value In lawsuit of failure,AssertionFailedError elisionwill be drop as seen below: 10. assertIterableEquals () Use Assertions.assertIterableEquals() method, if you need to assert that the actual and look iterables are deep adequate. It means the total number of elements and the order of actual and await should be equal. assertThrows () supports Iterable target as argument. It likewise supports error messages to be passed as an disceptation in case of examination failure. Syntax: Program: First assert will surpass as firstList and secondList have the like routine of component and are in the same order. Second assert will pass as firstList and thirdList have the same turn of elements but are not in the same order. In example of failure, AssertionFailedError exception will be thrown in the following manner: 11. assertThrows () Use Assertions.assertThrows () method, if you need to verify that the supplied executable throws an exception of the expected type and returns the elision. assertThrows () endorse only exclusion classes and executable as parameters. It besides supports error messages to be passed as an controversy in case of test failure. Syntax: Program: First assert will pass as expected Exception eccentric and the error drop by the practicable are the same. Second assert will neglect as expect Exception eccentric and the mistake drop by the executable are different. In lawsuit of failure, AssertionFailedError exception will be thrown in the following manner: 12. assertTimeout () Use Assertions.assertTimeout () method, if you need to assert that the execution of the scheme under exam is completed before the specified timeout is exceeded. assertTimeout () support Duration object, ThrowingSupplier object or an executable. It too supports erroneousness substance to be surpass as an argument in case of examination failure. Syntax: Program: In case of failure, AssertionFailedError exception will be cast in the following manner: 13. assertTimeoutPreemptively () In assertTimeoutPreemptively() method, execution of the Executable or ThrowingSupplier will be preemptively aborted if the timeout is exceeded. assertTimeout () back Duration object, ThrowingSupplier object or an executable. It also supports mistake messages to be surpass as an disceptation in case of test failure. Syntax: Program: In case of failure, AssertionFailedError exception will be thrown in the next way: 14. fail () Use Assertions.fail () method, if you need to fail a particular method with the supplied content as well as the underlie cause of the failure. fail () back String and Throwable values as parameters. Syntax: fail (String message) fail (String message, Throwable cause) Program: In case of failure, AssertionFailedError exception will be thrown in the following manner: There you have it. 14 different examples on how to use different types of JUnit Assertions for Selenium Tests. Ensure that pertain to our documentation while you ’ re running your 1st Selenium exam with JUnit 5 on is a cloud-based testing platform that enables developers and QA teams to run Selenium automation on real browsers and roving device hosted in distant data heart. It integrate seamlessly with Selenium (via), allowing cross-browser and cross-device testing without maintaining a local device lab. Key Features of BrowserStack: JUnit assertions validate trial outcomes and ascertain your Selenium tryout scripts are both reliable and meaningful. By using a multifariousness of asseveration like assertEquals, assertTrue, and assertThrows, you can systematically verify UI behavior and get regressions early in the development cycle. To further enhance your Selenium testing, run JUnit tests on BrowserStack. This allows teams to run cross-browser and cross-device tests under real user conditions without managing base. In addition, parallel execution helps reduce overall test duration, while CI integration enable continuous test within development pipelines. # Ask-and-Contributeabout this topic with our Discord community. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed. Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.Understanding JUnit asseveration for Selenium Testing with Examples
Overview
What are Assertions in Selenium Testing?
Different types of Asserts
Hard Assert
Soft Assert
Benefits of JUnit5 over JUnit4
Adding JUnit Library, JUnit5 and Maven Dependencies
& lt; dependency & gt; & lt; groupId & gt; org.seleniumhq.selenium & lt; /groupId & gt; & lt; artifactId & gt; selenium-java & lt; /artifactId & gt; & lt; version & gt; 4.3.0 & lt; /version & gt; & lt; /dependency & gt; & lt; dependency & gt; & lt; groupId & gt; io.github.bonigarcia & lt; /groupId & gt; & lt; artifactId & gt; webdrivermanager & lt; /artifactId & gt; & lt; version & gt; 5.2.1 & lt; /version & gt; & lt; /dependency & gt; & lt; dependency & gt; & lt; groupId & gt; org.junit.jupiter & lt; /groupId & gt; & lt; artifactId & gt; junit-jupiter-engine & lt; /artifactId & gt; & lt; adaptation & gt; 5.0.0 & lt; /version & gt; & lt; scope & gt; compile & lt; /scope & gt; & lt; /dependency & gt;
JUnit5 Assertions Class Methods
assertEquals (int wait, int actual) assertEquals (Object await, Object actual) assertEquals (Object anticipate, Object actual, String message)
public class AssertionsTest {static WebDriver driver; static String url = `` http: //automationpractice.com/index.php ''; WebElement wb=driver.findElement (By.xpath (`` //span [@ class='shop-phone '] //i [@ class='icon-phone '] /following-sibling: :strong '')); @ BeforeAll public inactive void setUp () {WebDriverManager.chromedriver () .setup (); driver = new ChromeDriver (); driver.manage () .window () .maximize (); driver.get (url);} @ Test @ DisplayName (`` AsserEquals demo '') public vacancy assertEquals () {//This will betray Assertions.assertEquals (`` 0123-23456 '', wb.getText ()); Assertions.assertEquals ('S ', 'S '); //This will miscarry Assertions.assertEquals (`` JUnit5 '', `` JUnit4 '', `` Strings are not equal '');}}assertNotEquals (Object unexpected, Object genuine) assertNotEquals (Object unexpected, Object actual, String message)
@ Test @ DisplayName (`` AsserNotEquals demo '') public void assertNotEquals () {//This will fail Assertions.assertNotEquals (`` 0123-456-789 '', wb.getText ()); Assertions.assertNotEquals (`` JUnit5 '', `` JUnit4 ''); Assertions.assertNotEquals ('S ', 'T ');}assertArrayEquals (int expected, int actual)assertArrayEquals(Object expected, Object actual) assertArrayEquals (int expected, int literal, String message)
@ Test @ DisplayName (`` AssertArrayEquals demo '') public vacancy assertArrayEquals () {int [] array1 = {1, 2, 3}; int [] array2 = {2, 3, 1}; //This will fail Assertions.assertArrayEquals (array1, array2);}assertNull (Object actual) assertNull (Object literal, String message)
@ Test @ DisplayName (`` AssertNull demo '') public nihility assertNull () {Assertions.assertNull (void); //This will fail Assertions.assertNull (wb.getText ());}assertNotNull (Object actual) assertNotNull (Object actual, String message)
@ Test @ DisplayName (`` AssertNotNull demonstration '') public vacancy assertNotNull () {Assertions.assertNotNull (wb.getText ()); //This will neglect Assertions.assertNotNull (null);}assertSame (Object expected, Object literal) assertSame (Object expected, Object genuine, String message)
@ Test @ DisplayName (`` AssertSame demo '') public void assertSame () {String s1= '' JUnit is great! ``; String copy=s1; String s2= '' JUnit is fun! ``; Assertions.assertSame (s1, transcript); //This will neglect Assertions.assertSame (s1, s2);}assertNotSame (Object unexpected, Object actual) assertNotSame (Object unexpected, Object actual, String message)
@ Test @ DisplayName (`` AssertNotSame demonstration '') public void assertNotSame () {String s1= '' Selenium ''; String copy=s1; String s2= '' Playwright ''; //This will betray Assertions.assertNotSame (s1, copy); Assertions.assertNotSame (s1, s2);}assertTrue (boolean condition) assertTrue (boolean condition, String message)
@ Test @ DisplayName (`` AssertTrue demonstration '') public void assertTrue () {Assertions.assertTrue (true); //This will miscarry Assertions.assertTrue (5 & lt; 0); Assertions.assertTrue (wb.isDisplayed ());}assertFalse (boolean condition) assertFalse (boolean condition, String message)
@ Test @ DisplayName (`` AssertFalse demo '') public void assertFalse () {Assertions.assertFalse (false); Assertions.assertFalse (5 & lt; 0); //This will miscarry Assertions.assertFalse (wb.isDisplayed (), `` Expected web element not to be displayed '');}assertIterableEquals (Iterable & lt;? & gt; await, Iterable & lt;? & gt; literal) assertIterableEquals (Iterable & lt;? & gt; expected, Iterable & lt;? & gt; genuine, String message)
@ Test @ DisplayName (`` AssertIterableEquals demonstrate '') public void assertIterableEquals () {final List & lt; Integer & gt; firstList = Arrays.asList (1, 2, 3); final List & lt; Integer & gt; secondList = Arrays.asList (1, 2, 3); last List & lt; Integer & gt; thirdList = Arrays.asList (3, 1, 2); Assertions.assertIterableEquals (firstList, secondList); //This will fail Assertions.assertIterableEquals (firstList, thirdList);}assertThrows (Class & lt; T & gt; expectedType, Executable executable) assertThrows (Class & lt; T & gt; expectedType, Executable executable, String message)
@ Test @ DisplayName (`` AssertThrows demo '') public void assertThrows () {Throwable ex =Assertions.assertThrows (IllegalArgumentException.class, () - & gt; {throw new IllegalArgumentException ();}); //This will miscarry Throwable exc=Assertions.assertThrows (IllegalArgumentException.class, () - & gt; {shed new NullPointerException ();});}assertTimeout (Duration timeout, Executable executable) assertTimeout (Duration timeout, Executable executable, String substance)
@ Test @ DisplayName (`` AssertTimeout demo '') public vacuum assertTimeout () {Assertions.assertTimeout (Duration.ofMinutes (1), () - & gt; {return `` testresult '';}); Assertions.assertTimeout (Duration.ofMillis (100), () - & gt; {Thread.sleep (200); return `` testresult '';});}assertTimeoutPreemptively (Duration timeout, Executable executable) assertTimeout Preemptively (Duration timeout, Executable practicable, String message)
@ Test @ DisplayName (`` AssertTimeoutPreemptively demo '') public nullity assertTimeoutPreemptively () {Assertions.assertTimeoutPreemptively (Duration.ofMinutes (1), () - & gt; {revert `` testresult '';}); Assertions.assertTimeoutPreemptively (Duration.ofMillis (100), () - & gt; {Thread.sleep (200); return `` testresult '';});}@ Test @ DisplayName (`` Fail demonstration '') public void Fail () {Assertions.fail (`` This method is miscarry '');}Running Selenium examination with JUnit5 on BrowserStack
Conclusion
Related Guides
Automate This With SUSA
Test Your App Autonomously