Assert and Verify Methods in Selenium

Related Product On This Page Difference between Assert and Verify in SeleniumMay 04, 2026 · 12 min read · Tool Comparison

Related Product

Assert and Verify Methods in Selenium

Selenium is a rich browser mechanisation tool. However, it doesn ’ t have potent statement methods. Assertions are necessary to verify test solution against wait result. So, they are vital for test automation. In, since there is no built-in assert method. The workaround to perform assertion in Selenium is to use a testing framework such as TestNG, JUnit or Python ’ s unittest.

Overview

Difference between Hard and Soft Assert in Selenium

  • Assert (Hard Assertion) → Stops trial if condition fails.
  • Verify (Soft Assertion) → Continues test execution, logs failure, reports at the end.

Difficult Assertions in Selenium

  • assertEquals ()→ Actual = Expected
  • assertNotEquals ()→ Actual ≠ Expected
  • assertTrue ()→ Condition = True
  • assertFalse ()→ Condition = False
  • assertNull ()→ Value is Null
  • assertNotNull ()→ Value is not Null

If condition fails →trial aborts directly.

Soft Assertions (Verify) in Selenium

  • Don ’ t abort on failure.
  • Collect all results.
  • Must call assertAll ()at the end to view failures.
  • Great for UI & amp; multiple validations.

Example Use Cases of Hard and Soft Assert in Selenium

  • Hard Asserts→ Login authentication, payment processing.
  • Soft Asserts→ Multiple UI checks, battlefield validations.

In this tutorial, learn the difference between assert and verify and the why, when, and how of using these methods to do Selenium test more efficient.

Difference between Assert and Verify in Selenium

  • In the case of, if the assert condition is not met, prove causa executing will be abort. The remaining tests are jump, and the test instance is mark as failed. These assertions are employ as checkpoints for examine or corroborate business-critical proceedings.
  • Tests will proceed to run in case of verification until the last test is executed, even if assert weather are not met.
  • Verify or Soft Asserts will report the errors at the end of the tryout. Simply put, tests will not be aborted if any stipulation is not met.
  • Testers need to invoke theassertAll ()method to watch the answer.

Assertions (also known as Asserts)

The word Assertagency to state a fact or opinion confidently or forcefully. In Selenium, Asserts are establishment or checkpoints for an application. Assertions state confidently that application behavior is working as expected. Asserts in Selenium validate the that help quizzer realise if tests have legislate or failed.

Types of Assertions

  • Difficult Assertions
  • Soft Assertions (Verify Method)

Hard Asserts vs Soft Asserts

Hard AssertionsSoft Assertions
Test Execution will be aborted if the assert condition is not metTest execution will keep till the end of the test case even if the assert condition is not met
Does not have to invoke any method to capture the assertionsTo view assertions result at the end of the test, the tester has to invokeassertAll ()

Difficult Assertions

Difficult Assertions are one in which test execution is aborted if the tryout does not encounter the assertion condition. The test case is marked as failed. In lawsuit of an assertion error, it will throw the “java.lang.AssertionError” exception.

Let ’ s explore different types of difficult asseveration with example.

assertEquals ()is a method that takes a minimum of 2 controversy and compares actual results with expected result. If both lucifer, the assertion is passed, and the test instance is marked as passed.assertEquals ()can compare Strings, Integers, Doubles, and many more variables, as shown in the ikon below.

Below is an example ofassertEquals ().

package com.tests;







import inactive org.testng.Assert.assertEquals;



import org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



importation org.testng.annotations.Test;







public class BrowserStackTutorials {



    @Test



public void testAssertEquals () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



String actualTitle = driver.getTitle ();



String expectedTitle = `` Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack '';



assertEquals (actualTitle, expectedTitle, `` Page title do not match the expected value '');



driver.quit ();



    }



}

assertEquals (actualTitle, expectedTitle, & # 8220; Page rubric execute not match the expected value & # 8221;);:

  • This averment compares the actual title (actualTitle) retrieved from the webpage with the expected title (expectedTitle).
  • If the two titles match, the tryout case proceeds.
  • If the titles do not match, the statement fails and halts further executing of the exam case.
  • The 3rd parameter, & # 8220;Page rubric does not match the expected value& # 8220;, is a custom erroneousness content displayed when the asseveration neglect.

assertNotEquals ()

assertNotEquals ()is a method that does the opponent of theassertEquals ()method. In this cause, the method equate the actual and expected result. But if the assertion condition is met if the two are not identical. The tryout event is marked as passed if actual and expected resultant are not the same.

Pro tip: Tools like SUSA can handle this autonomously — upload your app and get results without writing a single test script.

Code Snippet for assertNotEquals () in Selenium

software com.tests;







import unchanging org.testng.Assert.assertNotEquals;



meaning org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



import org.testng.annotations.Test;







public form BrowserStackTutorials {



    @Test



public void testAssertNotEquals () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



String actualTitle = driver.getTitle ();



String expectedTitle = `` Wrong Title '';



assertNotEquals (actualTitle, expectedTitle, `` Titles should not agree, but they do '');



driver.quit ();



    }



}

assertNotEquals (actualTitle, expectedTitle, & # 8220; Titles should not match, but they do & # 8221;);:

  • This statement checks that the actual rubric (actualTitle) retrieved from the webpage does not jibe the expected title (expectedTitle).
  • If the titles are different, the assertion passes, and the test continues.
  • If the titles match, the assertion miscarry, and the tradition error message & # 8220;Titles should not match, but they do& # 8221; is expose.

assertTrue ()

This Assertion verifies the Boolean value regress by the condition. If the Boolean value is true, then the affirmation passes the test case.

Code Snippet for assertTrue () in Selenium

software com.tests;







import static org.testng.Assert.assertTrue;



import org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



signification org.testng.annotations.Test;







public grade BrowserStackTutorials {



    @Test



public void testAssertTrue () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



boolean verifyTitle = driver.getTitle () .equalsIgnoreCase (`` Most Honest App & amp; Cross Browser Testing Platform | BrowserStack '');



assertTrue (verifyTitle, `` The page title is not as expected '');



driver.quit ();



    }



}

assertTrue (verifyTitle, & # 8220; The page rubric is not as expected & # 8221;);:

  • This assertion checks whether the stipulation inverifyTitleevaluates to true.
  • verifyTitleis a boolean variable that compares the actual title of the webpage with the expected title in a case-insensitive manner.
  • If verifyTitleis true, the assertion walk, and the examination return.
  • If verifyTitleis mistaken, the assertion neglect, and the tradition erroneousness message & # 8220;The page title is not as ask& # 8221; is displayed.

assertFalse ()

This method works the opposite ofassertTrue (). The Assertion verifies the Boolean value revert by the condition. If the Boolean value is mistaken, the asseveration surpass the exam case.

Code Snippet for assertFalse () in Selenium

package com.tests;







import stable org.testng.Assert.assertFalse;



import org.openqa.selenium.WebDriver;



signification org.openqa.selenium.chrome.ChromeDriver;



import org.testng.annotations.Test;







public class BrowserStackTutorials {



    @Test



public void testAssertFalse () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



boolean verifyTitle = driver.getTitle () .equalsIgnoreCase (`` Incorrect Title '');



assertFalse (verifyTitle, `` The rubric matched an incorrect value '');



driver.quit ();



    }



}

assertFalse (verifyTitle, & # 8220; The rubric fit an incorrect value & # 8221;);:

  • This asseveration checks whether the status inverifyTitleevaluates to false.
  • verifyTitleis a boolean variable that compares the actual title of the webpage with an incorrect rubric (& # 8220;Incorrect Title& # 8220;) in a case-insensitive manner.
  • If verifyTitleis mistaken, entail the actual title make not gibe the incorrect rubric, the assertion walk, and the trial continues.
  • If verifyTitleis true, meaning the actual title matches the incorrect rubric, the asseveration fails, and the custom error substance & # 8220;The title matched an incorrect value& # 8221; is displayed.

Code Tip: Want to run a quick test of the above code on our cloud infrastructure?

Talk to an Expert

assertNull ()

This method verifies if the look yield is null. If not, the value returned is mistaken.

Code Snippet for assertNull () in Selenium

package com.tests;







meaning static org.testng.Assert.assertNull;



import org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



import org.testng.annotations.Test;







public family BrowserStackTutorials {



    @Test



public void testAssertNull () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



String verifyAssertNull = null;



assertNull (verifyAssertNull, `` Expected value is not null '');



driver.quit ();



    }



}

assertNull (verifyAssertNull, & # 8220; Expected value is not null & # 8221;);:

  • This asseveration checks if the value of the variableverifyAssertNull is null.
  • In this example,verifyAssertNullis explicitly set to null.
  • If verifyAssertNullis so void, the statement passes, and the test continues.
  • If verifyAssertNullis not null, the assertion fails, and the custom error substance & # 8220;Expected value is not null& # 8221; is displayed.

assertNotNull ()

This method works opposite to the assertNull () method. The assertion stipulation is met when the method validates the expected output to be not void.

Code Snippet for assertNotNull () in Selenium

package com.tests;







meaning electrostatic org.testng.Assert.assertNotNull;



import org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



import org.testng.annotations.Test;







public class BrowserStackTutorials {



    @Test



public void testAssertNotNull () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



String actualTitle = driver.getTitle ();



assertNotNull (actualTitle, `` Page rubric should not be null '');



driver.quit ();



    }



}

assertNotNull (actualTitle, & # 8220; Page rubric should not be null & # 8221;);:

  • This assertion verify that the value of theactualTitlevariable is not null.
  • The actualTitleis obtained by callingdriver.getTitle (), which retrieves the rubric of the webpage at.
  • If actualTitleis not null, the assertion passes, and the test proceed.
  • If actualTitleis void (i.e., if the page did not laden or no title was retrieved), the statement fails, and the message & # 8220;Page title should not be null& # 8221; is expose.

Soft Assertions

In a hard averment, when the assertion fails, it terminates or aborts the examination. If the quizzer execute not want to terminate the script, they can not use difficult asseveration. To overcome this, one can use soft assertions.

Code Snippet for Soft Assertions in Selenium

package com.tests;







import org.openqa.selenium.WebDriver;



signification org.openqa.selenium.chrome.ChromeDriver;



signification org.testng.annotations.Test;



import org.testng.asserts.SoftAssert;







public grade BrowserStackTutorials {



    @Test



public nothingness testSoftAssert () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



SoftAssert softAssert = new SoftAssert ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');



String actualTitle = driver.getTitle ();



softAssert.assertEquals (actualTitle, `` Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack '', `` Title does not twin '');



softAssert.assertNotEquals (actualTitle, `` Incorrect Title '', `` Title matches an incorrect value '');



softAssert.assertNotNull (actualTitle, `` Page title should not be null '');



boolean titleMatch = actualTitle.equalsIgnoreCase (`` Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack '');



softAssert.assertTrue (titleMatch, `` Title does not pair in case-insensitive comparison '');



softAssert.assertAll (); // Reports all assertion results



driver.quit ();



    }



}
  • SoftAssert softAssert = new SoftAssert ();creates an instance ofSoftAssertto do soft statement.
  • softAssert.assertEquals (& # 8230;):Verifies if the actual rubric check the expected rubric. Fails with a custom message if the condition is false.
  • softAssert.assertNotEquals (& # 8230;):Ensures that the real title does not match an incorrect value.
  • softAssert.assertNotNull (& # 8230;):Confirms that the retrieved title is not void.
  • softAssert.assertTrue (& # 8230;):Validates that the rubric matches the expected value in a case-insensitive manner.
  • softAssert.assertAll ():Collects and reports all the assertion results. Without this line, betray assertion would not be describe.

Implementing Soft Assertions Without a Library

It is possible to enforce soft assertions without relying on library like TestNG or JUnit. The thought hither is to manually becharm assertion results during test execution to account all of them at the end. Now, even after an asseveration fails, you must continue test execution. At the end of the test, control all the asseveration and describe them.

Here is how soft assertions can be implemented manually:

  • Create a appeal to store assertion results: This could be a lean of custom-made averment results that track whether each assertion passed or fail.
  • Perform assertions and collect results: Instead of cast an elision immediately when an assertion fails, store the result (pass or fail) and continue the exam.
  • At the end of the test, report all assertions: After the exam has finished executing, iterate through the collection and story all statement results.

Example of Manual Soft Assertion Implementation

package com.tests;







import org.openqa.selenium.WebDriver;



import org.openqa.selenium.chrome.ChromeDriver;



import org.testng.annotations.Test;



import java.util.ArrayList;



meaning java.util.List;







public category BrowserStackTutorials {







// Custom class to hold assertion result info



static class AssertionResult {



boolean passed;



String substance;





AssertionResult (boolean passed, String message) {



this.passed = legislate;



this.message = message;



        }



    }







    @Test



public void testManualSoftAssert () {



System.setProperty (`` webdriver.chrome.driver '', `` C: \\I2EWebsiteTest\\Driver\\chromedriver.exe '');



WebDriver driver = new ChromeDriver ();



driver.navigate () .to (`` https: //www.browserstack.com/ '');





// List to collect assertion event



List & lt; AssertionResult & gt; assertionResults = new ArrayList & lt; & gt; ();







// Manually execute assertions and cod termination



String actualTitle = driver.getTitle ();



String expectedTitle = `` Most Reliable App & amp; Cross Browser Testing Platform | BrowserStack '';







// Check if title is as look (assertion)



if (actualTitle.equals (expectedTitle)) {



assertionResults.add (new AssertionResult (true, `` Title match as expected ''));



        } else {



assertionResults.add (new AssertionResult (false, `` Title does not mate the expected value ''));



        }







// Check if rubric is not void (assertion)



if (actualTitle! = null) {



assertionResults.add (new AssertionResult (true, `` Title is not null ''));



        } else {



assertionResults.add (new AssertionResult (false, `` Title is null ''));



        }







// Additional checks can be add as needed



boolean isTitleContainsKeyword = actualTitle.contains (`` BrowserStack '');



if (isTitleContainsKeyword) {



assertionResults.add (new AssertionResult (true, `` Title incorporate 'BrowserStack ' ''));



        } else {



assertionResults.add (new AssertionResult (false, `` Title does not contain 'BrowserStack ' ''));



        }







// At the end of the test, report all assertion results



for (AssertionResult termination: assertionResults) {



if (result.passed) {



System.out.println (`` PASSED: `` + result.message);



            } else {



System.out.println (`` FAILED: `` + result.message);



            }



        }







driver.quit ();



    }



}
  • Custom AssertionResult class: This class stores whether the statement passed or neglect and the associated substance.
  • Storing results in a lean: For each assertion, we create anAssertionResultand add it to theassertionResults list.
  • No immediate test failure: Instead of throwing an exception when an assertion fail, we proceed testing and store the results.
  • Report assertion at the end: After all averment feature been fulfil, we loop through the collected results and print whether each averment pass or betray.

Here, you must manually implement each assertion and effect collection, which increases code complexity. Also, if you forget to check the results at the end, the failed assertions may not stop the tryout. So, review the effect cautiously.

Conclusion

  • Hard and Soft Assertions are very crucial for designing and running tests.
  • They are instrumental in verifying application behavior at critical stages.
  • By using assertions, testing teams can determine if an covering is working as expected.
  • They can also save squad the trouble of running tests that don ’ t need to be run if a condition is not met.

It is recommended to run tests on for better accuracy as it takes into report. BrowserStack gives you access to 3000+ existent devices and browsers to test on. It allows you to run examination on multiple browser-device combinations simultaneously employ on its.

Tags
41,000+ Views

# Ask-and-Contributeabout this theme with our Discord community.

Related Guides

Automate This With SUSA

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts needed.

Try SUSA Free

Test Your App Autonomously

Upload your APK or URL. SUSA explores like 10 real users — finds bugs, accessibility violations, and security issues. No scripts.

Try SUSA Free