• Jobs
  • About
  • Common Assertions using WebDriver September 23, 2011

    In the previous sections of this User Guide, we saw how to instantiate a new browser session using the WebDriver API and how to locate page elements.

    The next action you will most likely want to perform are adding validation points, or assertions, in your test automation solution. The common types of validations are:

    • Is the page title as expected
    • Validations against an element on the page
    • Does text exist on the page
    • Does a javascript call return an expected value

    Let us look at how to achieve each of these using the WebDriver API.

    Page Title

    You can get the current page title simply by calling getTitle() on the WebDriver instance. Here is how a simple test would look like:

    public void pageTitle() {
        String pageTitle = driver.getTitle();
        assertEquals("Current page title", "Reference Web App - QA Automation", pageTitle);

    Validations against an element

    Text within an element

    There are two approaches you can use for validating text within an element. The first approach is find the element using one of the locator strategies and then call getText() on the element object returned.

    WebElement header = driver.findElement(By.id("header"));
    assertEquals("Header text", "Reference Web App", header.getText());

    The second approach is to search for an element using the text in the locator and check if it is not null.

    WebElement header = driver.findElement(
            By.xpath("//div[@id=\"header\" and normalize-space(.)=\"Reference Web App\"]"));
    assertNotNull("Header text", header);

    In this example I used xpath but you could use other locators like linkText or partialLinkText.

    Attributes of the element

    This is similar to validating text in the element. You would find the element on the page and then use getAttribute

    WebElement submit = driver.findElement(By.name("submit"));
    assertEquals("Submit button value", "Login", submit.getAttribute("value"));

    Does text exist in the entire page

    For those who start with Selenium 2, or who have used Selenium 1.x, you would expect to easily find a doesTextExist method. It will come as a bit of a shock that there isn’t something as obvious in the API.

    One option to get the text representation of the entire page is getting the text of the body element using something like


    Unfortunately, getting text using this mechanism is extremely slow for large pages. The second option is to get the html content using driver.getPageSource() and then pass it to a html parser. One such a parser is JSoup.

    • easy to use,
    • is better performant for this sort of thing, and
    • the output text is cleaner and easier do validations against

    . Here is how you would use it:

        public String getPageContent() {
            Document doc = Jsoup.parse(driver.getPageSource());
            return doc.text();

    Just to compare the two approaches, getting document text in msn.com took over 5 secs using first approach and less than a second for the second.

    Ofcourse for this code to work, you will have to download the jsoup library and put it in your classpath. Also if you are not developing in java you will have to find a different parser because jsoup is a java library that hasn’t been ported to other languages.

    Validating Javascript return values

    There are various reasons why you might want to directly call a javascript method or get the value of a javascript variable on the page. You can do this using only those WebDriver instances that implement the JavascriptExecutor interface. The JavascriptExecutor interface has a executeScript method that you would pass your javascript call. If you expect a return value, your javascript snippet must have a return.

    Let’s look at an example:

    driver.get(REFERENCE_APP_URL + "jsmethods.php");
    String returnValue = (String) ((JavascriptExecutor) driver).executeScript("return getString();");
    assertEquals("JS method with string return type", "foo", returnValue);

    The return type for executeScript method is Object. That is because this script would return an object of different types based on what is returned. The various types of objects returned are Sting, Integer, Boolean, etc. It also can return a WebElement as we saw in the Locating page elements using WebDriver under DOM locator.

    Besides these types of validations, there are certainly others you can have, like if a new window was opened, an alert dialog popped up, a cookie was set etc. We will cover those in later sections of the Selenium 2 User Guide.

    Posted by Rahul Poonekar in : Selenium

    10 responses to “Common Assertions using WebDriver”

    1. Apoorva says:

      I try to fetch the text by this method as you suggest , and here is the code:

      WebElement b= driver.findElement(By.xpath(“//*[@id=’rgSGSec.′]”));
      String d = b.getText();
      System.out.println(“The Text is:” +d);

      but it is not able to locate the element and I am getting the exception as :
      Unable to locate element: {“method”:”id”,”selector”:”rgSGSec.2.2″}; duration or timeout: 30.81 seconds

      Please help me.

    2. Apoorva says:

      One more think i forgot to mention in above mail that when i have used
      WebElement b= driver.findElement(By.xpath(“//*[@id=’rgSGSec.′]“)).click();
      It is able to locate the element but when i tried to fetch its text by getText() method , it is not able to convert its void to text format.

      Please tell me how can i get text for a particular element without using clicking method and able to store in String or boolean format.

    3. Amit says:

      getText is a function defined in browserbot for selenium 1. with webdriver browserbot is not able. so you are not able to use gettext();

    4. Rahul Poonekar says:


      The WebElement class has a getText() method.

    5. Tarang says:

      Hi Rahul,

      I’ve recently started digging into Selenium 2.0. I’m a bit confused on the jar’s available in downloads section of Selenium site.
      1. Selenium Server
      2. The Internet Explorer Driver Server
      3. Selenium Client Drivers( Java/C#..)

      Currently I’m using only Selenium Server jar to develop my code in Java to run on IE. My question is what extra do I gain by using The Internet Explorer Driver Server and java Selenium Client Drivers jar’s as I’m able to perform all requisite operations without them as well?

    6. Tarang says:

      H Rahul,

      Are these assertions part of Webdriver or we are using JUnit to make these possible?

    7. SunilSharma says:

      I am using the below code to verify that none of the images present on webpage are not broken but getting error. Please suggest some idea to verify the same.

      Anticipating a positive response.


      int imageCount = driver.findElements(By.xpath(“//img”)).size();
      for (int i = 0; i < imageCount; i++) {
      String currentImage = "this.browserbot.getUserWindow().document.images[" + i + "]";

      ((JavascriptExecutor) driver).executeScript(("(!" + currentImage + ".complete) ? false : !(typeof " + currentImage + ".naturalWidth != \"undefined\" && " + currentImage + ".naturalWidth == 0);"), "true", "Broken image: .src");

      FAILED: testPageLoadError
      org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)
      Command duration or timeout: 47 milliseconds

    8. MTL says:

      Alternative to getText(); write a JavaScript; this should work

      String test = (String)((JavascriptExecutor)driver).executeScript(“return $(‘#id’).text()”);

      assuming you have an id for this; or make your changes accordingly. Pls observe JQuery in this piece.

    9. Ritika says:

      Hi i want to check all the validation on a page.

    10. Lakki says:


      instead of using getText() use element.getAttribute(“value”);

    Leave a Reply

    Your email address will not be published. Required fields are marked *