I am writing scenario test cases in cucumber and I want to check if all the elements of a PageObject are valid and selenium can interact with them, before I run the test. I want to avoid running my multi-step, long test case just to get to the last page and get an exception that an element is not found. I wanted to be able to test my PageObject after I write it, so I can be sure that all the elements are reachable (before running the long test..).
The website I am working on does not have consistent id tags and using @FindBy() sometimes takes some playing around with. I am trying to make a simple process of:
Do you know of a way to access all the PageObjects elements with out making a method for each one? A method that initializes all the elements?
After trying a number of different ways, I used reflection within the class to pull all fields, and then used .isPresent();
to check if the element is on the page. This solution requires this method to be placed in each class that you want to test, which I was trying to avoid.
Solution:
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features = "src/test/resources/features/checkElems")
public class RegressionTestSuite {}
Feature: Check if WebPage Object elements can be found
Scenario: Check if the page's elements are reachable
Given navigate to webpage
Then check page elements
public class CanFindElemsTest {
// Change the class
ClassYouAreTesting page;
@Given("^navigate to webpage$")
public void navigate_to_webpage() throws Exception {
page.open();
}
@Then("^check page elements$")
public void check_page_elements() throws Exception {
page.checkPageElementsExist();
}
}
public class SomeWebPage extends PageObject {
@FindBy(id = "someID")
private WebElementFacade someElement;
@FindBy(linkText = "some text")
private WebElementFacade someLink;
@FindBy(className = "some-class")
private WebElementFacade anotherElement;
public void checkPageElementsExist() throws Exception {
Field[] allFields = getClass().getDeclaredFields();
for (Field field : allFields) {
if (field.get(this) instanceof WebElementFacade) {
WebElementFacade f = (WebElementFacade) field.get(this);
if (!f.isPresent()) {
System.out.println("ElementNotFound: " + field.getName());
} else {
System.out.println("Found: " + field.getName());
}
}
}
}
}