Page Objects are a good way to produce a maintainable and reusable codebase to implement automated ui tests with selenium. Nevertheless those page objects can contain a lot of (selenium related) boilerplate code that is mostly reused via copy and paste. (like for example having fluent waits or Actions) This project provides processors to generate page object implementations by processing annotations placed on interfaces. By doing that it drastically increases readability of page objects and reduces time for development.
- generates page object class implementations based on annotated interfaces
- page objects support mixins - interfaces can extend multiple other interfaces and will inherit all of their elements and methods
- generates extraction data class implementations base on annotated interfaces.
- actions like clicking of elements or writing to input fields can be configured via annotations
- the api enforces creation of a fluent api that improves writing of tests. Doing assertions or executing of custom code is also embedded into this fluent api
The project is still in development, so it currently just supports a few Actions like clicking or writing to input fields. Nevertheless, it's quite simple to define custom Action annotations and their implementations.
Please create an issue, if you need specific action to be implemented. Usually it will be included shortly after ;)
The api lib must be bound as a dependency - for example in maven:
<dependencies>
<dependency>
<groupId>io.toolisticon.pogen4selenium</groupId>
<artifactId>pogen4selenium-api</artifactId>
<version>0.12.0</version>
<scope>provided</scope>
</dependency>
</dependencies>Additionally, you need to declare the annotation processor path in your compiler plugin:
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>io.toolisticon.pogen4selenium</groupId>
<artifactId>pogen4selenium-processor</artifactId>
<version>0.12.0</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>The page object interfaces must be annotated with the PageObject annotation and must extend the PageObjectParent interface.
There are basically two ways to reference elements. The first is to use element fields in the generated classes that will internally be initialized via Seleniums PageFactory.
To achieve that it's necessary to add String constants annotated with the PageObjectElement annotation for all web elements which are related with the page object. The constant values must be unique inside the interface and will be used in the generated class as variable names for the corresponding elements. The constant names must have "_ID" as suffix.
The other way is to use By locators on the fly by configuring them directly in the action annotations.
Those action annotations must be placed on PageObject interface methods or method parameters. Those methods must return another page object interface.
It's also possible to add methods to extract data. Those methods must be annotated with the ExtractData annotation and must return an instance or List of a data extraction type (see next section)
You are able to use default methods to use custom code.
Our example website is just a simple html file. This example demonstrates how to setup the page object:
@PageObject
public interface TestPagePageObject extends PageObjectParent<TestPagePageObject>{
static final String DATA_EXTRACTION_FROM_TABLE_XPATH = "//table//tr[contains(@class,'data')]";
TestPagePageObject writeToInputField(@ActionWrite(by=_By.ID, value="input_field") String value);
@ExtractDataValue(by=_By.ID, value = "input_field", kind=Kind.ATTRIBUTE, name="value")
String readInputFieldValue();
@ActionMoveToAndClick(by=_By.XPATH, value = "//fieldset[@name='counter']/input[@type='button']")
@Pause(value = 500L)
TestPagePageObject clickCounterIncrementButton();
@ExtractData(by = io.toolisticon.pogen4selenium.api._By.XPATH, value = DATA_EXTRACTION_FROM_TABLE_XPATH)
List<TestPageTableEntry> getTableEntries();
@ExtractData(by = io.toolisticon.pogen4selenium.api._By.XPATH, value = DATA_EXTRACTION_FROM_TABLE_XPATH)
TestPageTableEntry getFirstTableEntry();
@ExtractDataValue(by = _By.XPATH, value="//fieldset[@name='counter']/span[@id='counter']")
String getCounter();
// you can always provide your own methods and logic
default String providedGetCounter() {
return getDriver().findElement(org.openqa.selenium.By.xpath("//fieldset[@name='counter']/span[@id='counter']")).getText();
}
// Custom entry point for starting your tests
public static TestPagePageObject init(WebDriver driver) {
driver.get("http://localhost:9090/start");
return new TestPagePageObjectImpl(driver);
}
}Interfaces for data extraction must be annotated with the DataToExtract annotation. The methods for reading extracted data values must be annotated with the DataToExtractValue annotation. Like with selenium it's possible to use different mechanics to locate the web elements to read the values from. Please make sure to use to prefix xpath expressions with "./" to locate elements relative to the Root element for extraction defined in the page objects extraction method.
Extracting table data for our small example:
@DataObject
public interface TestPageTableEntry {
// will use XPATH locator by default if by attribute isn't set explicitly
@ExtractDataValue(by = _By.XPATH, value = "./td[1]")
String name();
@ExtractDataValue( value = "./td[2]")
String age();
@ExtractDataValue( value = "./td[3]/a", kind = Kind.ATTRIBUTE, name = "href")
String link();
@ExtractDataValue(, value = "./td[3]/a", kind = Kind.TEXT)
String linkText();
}Page Objects can also be used to create abstraction layers.
Think about the use case that you have to fill out a form where you have to fill out multiple fields belonging to an address. In this case it's likely that you want to create a Page Object that does some aggregations .
First you would create the Page Object that defines all actions
@PageObject
public class PersonalDataFormPageObject extends PageObjectParent<TestPagePageObject>{
PersonalDataFormPageObject writeName(@ActionWrite(by=_By.ID, value="name")String name);
PersonalDataFormPageObject writeStreet(@ActionWrite(by=_By.ID, value="street")String street);
PersonalDataFormPageObject writeHouseNumber(@ActionWrite(by=_By.ID, value="housenumber") String houseNumber);
PersonalDataFormPageObject writeZipCode(@ActionWrite(by=_By.ID, value="zipCode")String zipCode);
PersonalDataFormPageObject writeZipCode(@ActionWrite(by=_By.ID, value="city")String city);
}
Then you could create another page object later used in tests, that does some aggregation:
@PageObject
public class AggregatedPersonalDataFormPageObject extends PageObjectParent<AggregatedPersonalDataFormPageObject>{
default AggregatedPersonalDataFormPageObject writeAddress(Address address) {
this.changePageObjectType(PersonalDataFormPageObject.class)
.writeName(address.getName())
.writeStreet(address.getStreet())
.writeHouseNumber(address.getHouseNumber())
.writeZipCode(address.getZipCode())
.writeCity(address.getCity());
return this;
}
}It's a good practice to use such aggregation page objects to group actions that belong together to make the automation code base more readable.
Writing tests is easy. The fluent api provides a doAssertions method that allows you to inline custom assertions done with your favorite unit testing tool.
public class TestPageTest {
private WebDriver webDriver;
private JettyServer jettyServer;
@Before
public void init() throws Exception{
jettyServer = new JettyServer();
jettyServer.start();
webDriver = new EdgeDriver();
webDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));
}
@After
public void cleanup() throws Exception{
webDriver.quit();
jettyServer.stop();
}
@Test
public void extractDatasetsTest() {
TestPagePageObject.init(webDriver)
.doAssertions(e -> {
// Do assertions here
List<TestPageTableEntry> results = e.getTableEntries();
MatcherAssert.assertThat(results, Matchers.hasSize(2));
MatcherAssert.assertThat(results.getFirst().name(), Matchers.is("Max"));
MatcherAssert.assertThat(results.getFirst().age(), Matchers.is("9"));
MatcherAssert.assertThat(results.getFirst().link(), Matchers.is("https://de.wikipedia.org/wiki/Max_und_Moritz"));
MatcherAssert.assertThat(results.getFirst().linkText(), Matchers.is("Max und Moritz Wikipedia"));
MatcherAssert.assertThat(results.get(1).name(), Matchers.is("Moritz"));
MatcherAssert.assertThat(results.get(1).age(), Matchers.is("10"));
MatcherAssert.assertThat(results.get(1).link(), Matchers.is("https://de.wikipedia.org/wiki/Wilhelm_Busch"));
MatcherAssert.assertThat(results.get(1).linkText(), Matchers.is("Wilhelm Busch Wikipedia"));
});
}
@Test
public void extractFirstDatasetTest() {
TestPagePageObject.init(webDriver)
.doAssertions(e -> {
// Do assertions here
TestPageTableEntry result = e.getFirstTableEntry();
MatcherAssert.assertThat(result.name(), Matchers.is("Max"));
MatcherAssert.assertThat(result.age(), Matchers.is("9"));
MatcherAssert.assertThat(result.link(), Matchers.is("https://de.wikipedia.org/wiki/Max_und_Moritz"));
MatcherAssert.assertThat(result.linkText(), Matchers.is("Max und Moritz Wikipedia"));
});
}
@Test
public void incrementCounterTest() {
TestPagePageObject.init(webDriver)
.doAssertions(e -> {
MatcherAssert.assertThat(e.getCounter(), Matchers.is("1"));
})
.clickCounterIncrementButton()
.doAssertions(e -> {
MatcherAssert.assertThat(e.getCounter(), Matchers.is("2"));
})
.clickCounterIncrementButton()
.clickCounterIncrementButton()
.doAssertions(e -> {
MatcherAssert.assertThat(e.getCounter(), Matchers.is("4"));
});
}
}There are some default methods provided by the fluent api:
Gets the WebDriver in use. This is very useful in doAssertions or execute methods to manually execute selenium related code.
By using the verify methods it's possible to do check state of elements, i.e. if url matches a regular expression or if elements are present or clickable. Expected state is configured in PageObjectElement annotation. If not set explicitly all elements are expected to be present by default.
It's possible to inline assertions done via your favorite testing tools. By providing this method it's not necessary to hassle with local variables anymore.
The execute method allows you to execute code dynamically without loosing the context of the fluent api. This can be quite useful for reading data from the web page and doing things based on the extracted data.
Allows changing the page objects type if expected behavior leaves the 'happy path' - for example if you expect to encounter a failing form validation or similar things.
It's possible to enforce an explicit pause time by using this method
Wait as long as a specific text is present on page. The text can either be a static text or a localized text if it matches the following pattern '${key}'. Localization will internally provided by a thread local resource bundle. The resource bundle can be configured via the LocalizationUtilities class. This method is a great help to wait until the expected page is being loaded and is displayed.
It's possible to change the locale via this method
New action annotations can added by providing an action annotation annotated itself with the Action meta annotation. Annotations must either be applicable to methods or method parameters.
Please see the ActionWrite Annotation as an example
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Action(ActionWriteImpl.class)
public @interface ActionWrite {
/**
* The locator type to use. Can be ELEMENT for using a generated element or any kind of locator provided by Selenium.
* @return the locator to use.
*/
@LocatorBy
_By by() default _By.ELEMENT;
/** The locator string to use. */
@LocatorValue
String value();
/**
* The locator strategy to use, will just be taken into account if by attribute is not set to ELEMENT.
* @return the Locator strategy, defaults to DefaultLocatorStrategy
*/
@LocatorSideCondition
Class<? extends LocatorCondition> locatorSideCondition() default DefaultSideCondition.class;
}The Action annotation is used to bind an implementation for the action annotation. It's also possible to map annotation attributes to constructor methods.
The action implementation must extend the BaseAction class:
public class ActionWriteImpl extends BaseAction {
private final String toSet;
public ActionWriteImpl(WebDriver driver, SearchContext searchContext, LocatorCondition locatorCondition, String toSet) {
super(driver, searchContext, locatorCondition);
this.toSet = toSet;
}
@Override
public boolean checkCondition(WebDriver driver, WebElement element) {
return element.isDisplayed() && element.isEnabled();
}
@Override
public Collection<Class<? extends Throwable>> exceptionsToIgnore() {
return Arrays.asList(NoSuchElementException.class);
}
@Override
protected void applyAction(WebElement webElement) {
webElement.click();
webElement.sendKeys(Keys.CONTROL + "a");
webElement.sendKeys(Keys.DELETE);
webElement.sendKeys(toSet);
}
}It must have a constructor with at least the following parameters:
WebDriver driver, SearchContext searchContext, LocatorCondition locatorCondition
If the action can be applied to a method parameter, it must have an additional parameter:
WebDriver driver, SearchContext searchContext, LocatorCondition locatorCondition, String toSet
Additional annotation attributes can be mapped to constructor parameters call by using the Action annotations attributeNameToConstructorMapping attribute.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Action(value = ActionDragFromToImpl.class, attributeNameToConstructorMapping = {"fromBy", "fromValue"})
public @interface ActionDragFromTo {
/**
* The locator type to use. Can be ELEMENT for using a generated element or any kind of locator provided by selenium.
* @return the locator to use.
*/
_By fromBy() default _By.XPATH;
/** The locator string to use. */
String fromValue() default "${}";
@LocatorBy
_By toBy() default _By.XPATH;
/** The locator string to use. */
@LocatorValue
String toValue();
/**
* The locator strategy to use, will just be taken into account if by attribute is not set to ELEMENT.
* @return the Locator strategy, defaults to DefaultLocatorStrategy
*/
@LocatorSideCondition
Class<? extends LocatorCondition> locatorSideCondition() default DefaultSideCondition.class;
}There are a few things you should consider as best practices
- Use a multi layer approach. The lowest layer should provide all actions that can be done on page
- Naming convention: Please use specific prefixes for you page object methods. This can be 'do' for all actions and 'get' for reading data.
- Page objects should define just the happy path. Special cases like failing validations can be handled in the unit tests via the execute method(you can change the page object type via the changePageObjectType method in it).
Please check the our example submodule: example
It contains a basic example page demonstrating the usage of all available actions and data extraction. A second example shows how to test the google search page.
We welcome any kind of suggestions and pull requests.
The pogen4selenium is built using Maven.
A simple import of the pom in your IDE should get you up and running. To build the pogen4selenium on the commandline, just run mvn or mvn clean install
The likelihood of a pull request being used rises with the following properties:
- You have used a feature branch.
- You have included a test that demonstrates the functionality added or fixed.
- You adhered to the code conventions.
This project is released under the revised MIT License.
This project includes and repackages the Annotation-Processor-Toolkit released under the MIT License.