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 the message Element WebElement message = driver.findElement(By.id("message")); // Get the message elements text String messageText = message.getText(); // Verify message element's text displays "Click on me and my // color...