Checking an element's text
While testing a web application, we need to verify that elements are displaying correct values or text on the page. Selenium WebDriver's WebElement API provides various ways to retrieve and verify text. Sometimes, we need to retrieve text or value 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 by using the WebElement class' getText()
method
.
How to do it...
Here, we will create a test that locates an element and then retrieves text from the element in a string variable. We will verify contents of this string for correctness.
@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 will change" assertEquals("Click on me and my color...