Checking an element's text

While testing a web application, we need to verify that elements are displaying the correct values or text on the page. Selenium WebDriver's WebElement interface provides methods to retrieve and verify text from an element. Sometimes we need to retrieve text or values from an element into a variable at runtime and later use it at some other place in the test flow.

In this recipe, we will retrieve and verify text from an element using the getText() method of the WebElement interface.

How to do it...

Here, we will create a test that finds an element and then retrieves text from the element in a string variable. We will verify the contents of this string for correctness using the following code:

@Test public void testElementText() ...

Get Selenium Testing Tools Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.