Selenium supports many different HTML element locator strategies such as CSS, class, ID, and XPath. Xpath in my opinion is provides you with the most flexibility as it has features such as axes (build-in functions) and conditional operators. It would be hard to find an element you couldn’t capture in a sensible way with Xpath but it all depends on how good you’re with Xpath. So if you’re a test framework developer it makes sense for you to abstract out some of the common XPath templates into new By classes. Apart from reducing the chances of inexperienced test engineers making mistakes with the Xpaths, you can increase the readability of the code and provide means for greater reusability (through mechanisms such as ByChained).
Test Layer
package com.dumiduh; | |
import com.dumiduh.constants.Constants; | |
import io.github.bonigarcia.wdm.WebDriverManager; | |
import org.openqa.selenium.chrome.ChromeDriver; | |
import org.testng.Assert; | |
import org.testng.annotations.AfterClass; | |
import org.testng.annotations.BeforeClass; | |
import org.testng.annotations.Test; | |
public class CustomeLocatorTest { | |
private static ChromeDriver driver; | |
@BeforeClass | |
public static void setup() { | |
WebDriverManager.chromedriver().setup(); | |
driver = new ChromeDriver(); | |
driver.get(Constants.DYNAMIC_LOAD); | |
} | |
@Test | |
public static void byContainsText() { | |
Assert.assertTrue(driver.findElement(CustomBy.containsText("Powered by")).isDisplayed(), "the expected text value was not found in the html document."); | |
} | |
@AfterClass | |
public static void cleanUp() { | |
driver.quit(); | |
} | |
} |
Custom By Locator
package com.dumiduh; | |
import org.openqa.selenium.By; | |
import org.openqa.selenium.SearchContext; | |
import org.openqa.selenium.WebElement; | |
import java.util.List; | |
public class CustomBy extends By { | |
private String searchTerm; | |
private final String XPATH = "//*[contains(text(),'%s')]"; | |
public static By containsText(String searchTerm) { | |
return new CustomBy(searchTerm); | |
} | |
private CustomBy(String value) { | |
this.searchTerm = value; | |
} | |
@Override | |
public List<WebElement> findElements(SearchContext context) { | |
return context.findElements(By.xpath(String.format(XPATH, searchTerm))); | |
} | |
} |
No comments:
Post a Comment