One of the things I’ve been trying to achieve during the creation of a framework for browser automation, is the capability of using best practices and methodologies that make code maintainable across test.
This is how Selenium folks describe it :
The PageFactory relies on using sensible defaults: the name of the field in the Java class is assumed to be the “id” or “name” of the element on the HTML page.
Then they add:
The driver instance that’s used is the one that’s passed to the PageFactory‘s initElements method.
I implemented this pattern and also I was able to use another powerful feature : Annotations. An annotation in this case is an attribute used to identify page elements using different combinations but at the end of the day you will have an IWebElement based on the annotation selected.
In order to explain how the PageFactory and the Annotations works, let’s look at the following class that performs the SignOn feature (and it is actually reused by several test). By looking at the HTML form, I’ve created an IWebElement for each field in the form and using annotations, I’ve indicated the way the element is going to be found.
This class contains a definition of all the HTML form fields of the SignUp page,therefore when the method PageFactory.InitElements is called, those fields are already initialized and you will have a IWebElement to work with. I forgot to mention that you can try to find an element using different attributes, please take a look at the following list:
The following code explains how an instance is created:
It’s important to say that this pattern also allows to take advantage of the Cache mechanism. If there are fields that never changed (are not tied to AJAX events), you can use the Cached version of the element and therefore improve the performance of the application.
By adopting this pattern we can make sure that if there are changes at the UI level (adding new fields or renaming them), there is just a place to look at. Moreover, this approach also allows a unified way to deal with the page elements.
So far I’ve been using it and I’m very optimistic about the results 🙂