Create custom locators to find element in WebDriver Java
In order to make our web application under test more testable, we approached dev and asked them to assign a custom attribute (say data-id to all the web components). The advantage of this approach is that, dev are now free to change any other attribute ( not data -id) as per the business requirement without breaking our UI automation tests.
Since data-id is a custom attribute that means, we have to use either By.xpath or By.Css and pass this data-id attribute every time.
Or Just imagine an application that has a lot of images with common attribute href.
To efficiently tackle this situation, we can create our own custom locatory strategy by extending it from By Class.
To give an example :-
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
public class ByImageSrc extends By
{
private final String imageByString;
public ByImageSrc(String imageByString)
{
this.imageByString = imageByString;
}
@Override
public List<WebElement> findElements(SearchContext context)
{
List<WebElement> mockElements = context.findElements(By.xpath("//img[@src='" + imageByString + "']"));
return mockElements;
}
}
To use this in POM class, WebElement element = driver.findElement(new ByImageSrc("/path/to/image"));
Comments
Post a Comment