liveBook · Manning

getText method

As explained in BDD in Action, Second Edition

The getText method is a WebDriver operation that retrieves the text content of a web element.

The getText method is a WebDriver operation that retrieves the text content of a web element so an automated acceptance test can verify what the UI displays. section 10.2.13 section 10.2.12

A typical verification flow is:

  • Locate the relevant element or collection with an ID, CSS selector, or XPath. section 10.2.12
  • Call getText() on each WebElement and collect the returned strings. section 10.2.12
  • Assert that the retrieved text matches the acceptance criterion, such as containing “Singapore.” section 10.2.12

Checking featured destinations

After locating the featured destination titles with the CSS selector #featured .destination-title, loop through the WebElements, add each getText() result to a list, and assert that the list contains “Singapore.” section 10.2.12

List<WebElement> destinations                                               #1
  = driver.findElements(By.cssSelector("#featured .destination-title"));    #1
List<String> destinationTitles = new ArrayList<String>();                   #2
for(WebElement destinationElement : destinations) {                         #3
    destinationTitles.add(destinationElement.getText());                    #3
}                                                                           #3
assertThat(destinationTitles).contains("Singapore");                        #4

View the complete Java example that locates destination titles, extracts their text with getText(), and verifies the expected destination. section 10.2.12

How BDD in Action, Second Edition covers it

How deep it goes
Explains retrieval from individual and multiple WebElements, then demonstrates collection and assertion, without detailing WebDriver internals.
Examples
Demonstrates verifying three featured destinations and checking that the extracted titles include Singapore.
What it assumes
Assumes familiarity with locating WebElements and collections while introducing text extraction and verification from zero.
What you can do after
Apply it via WebDriver to extract UI text and verify acceptance criteria against returned strings.
How it connects
Connects WebDriver and WebElement text retrieval with CSS selectors, XPath, collections, and acceptance criteria.

This explainer was generated by Manning's knowledge graph from the text of BDD in Action, Second Edition. The section links point to the parts of the book it draws on.