Implementing Assert and Verify logic in Selenium WebDriver


One of the actions that we always need to perform while doing test automation is to apply different assertions or verification to check results of automated tests. Selenium IDE has built in VerifyTextPresent, AssertElementPresent commands. But how we do it in Selenium WebDriver? There are definitely many ways to do it in Slenium WebDriver with support of testing frameworks like JUnit or TestNG etc. In this blog, I will discuss few of those approaches that can be used with Selenium WebDriver to..

  1. Verify/Assert Text Present
  2. Verify/Assert Element Present

1.1 Verify Text Present

In many test automation scenarios, before or after the test step we need to check if the specific text is displaying or not. We donot our test scripts to stop irrespective the result (text found or not). To achieve this objective, we have various approaches that can be used. In below I have shared some of the java code examples that can be used to implement this strategy.

1.2 Assert Text Present

Similarly, in testing scenarios where we want our scripts to stop if certain assertion fails, we can use assert methods from Junit, TestNG (and other alternative frameworks) to implement the assertion strategy. In below are some examples of assertions on text.

2.1 Verify Element Present

Selenium WebDriver has some built-in methods that can be used with TestNG or Junit methods to implement Element verification logic. Few code examples are given below.

2.2 Assert Element Present

IsElementPresent method from Selenium WebDriver API can be used together with AssertTrue method to implement Element assertion logic as demonstrated in code below.

Alternatively, If you want to assert Element Not Present, then you can use following example, which verifies that there are NO matching elements present in DOM and returns the value of zero. So when zero value is returned, assertion will pass. On other hand if there is any matching element present then zero will not be returned and assertion will fail.

End Note: These are just few of the verification/assertion methods. There are many other approaches as well to do it. Have you ever used these in your test automation scripts? Or would like to recommend a better approach to our readers! Please share your thoughts and experiences in comments section.

Arif Masood

Software Quality Professional. Perfectionist. Love to explore new tools, technologlies & processes. Worked on several web & mobile projects in last 7+ years. Mostly in areas of Functional, API, Automation & Performance testing. Ocassional blogger - trying to be more regular one :)



Show Buttons
Hide Buttons