Reputation: 171
I would like to implement my Own By
Class in order to have custom selectors. What are the pros and cons of using Custom Selectors
DEV code
<button class="btn js-AddNuts" type="button" testid="addbutton">
Here Selector is testid
Reason: We are planning to have test specific selectors and design Names for all the elements in DEV Code so that if they change anything in DEV it doesn't impact test.
Upvotes: 1
Views: 722
Reputation: 23805
As you know there is no problem with creating your own locator, Selenium provides the functionality to create custom locator. Basically selenium internally uses to locate element using xPath
when you are going to find element By.id
, By.name
etc. So you could create simply your own locator by extending By
class.
If you want to create a custom locator which locate element using testid
, you should create as below (Assuming you are using java) :-
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebElement;
class ByTestId extends By {
private final String testId;
public ByTestId(String testId) {
this.testId = testId;
}
@Override
public List<WebElement> findElements(SearchContext context) {
return context.findElements(By
.xpath(".//*[@testid = '"+testId+"']"));
}
@Override
public WebElement findElement(SearchContext context) {
return context.findElement(By
.xpath("//*[@testid = '"+testId+"']"));
}
}
Now you can easily locate element by using testid
as below :-
//for single webelement
WebElement element = driver.findElement(new ByTestId("addbutton"));
//for list of webelements
List<WebElement> elements = driver.findElements(new ByTestId("addbutton"));
Note : You can also locate the element in your custom By
class using By.cssSelector
as : By.cssSelector("*[testid = '"+testId+"']")
Hope it helps..:)
Upvotes: 0
Reputation: 25596
There is no need to create a custom locator in this case (or any case that I have run across or can think of). You can simply use the following code that uses a CSS Selector.
By.cssSelector("button[testid='addbutton']")
I would suggest that you spend some time reading and learning CSS Selectors. They are very powerful.
Upvotes: 1