Advanced Locator Abstraction in Java
Last week I wrote about How To Minimize The Pain Of Locator Breakage over at the Sauce Labs blog. The gist of it is don’t put your locators in the script, put them in a properties file. I still believe that whole-heartedly, but have a new variation of how to do it that further moves code out of the test class.
As a general rule of thumb, the less non-test code in the script itself the better.
This mechanism makes use of ‘static’ methods which can be called directly without first having to create the object itself. (Thus further preventing things from cluttering up the scripts.)
<pre lang="java">import java.io.InputStream;
import java.util.Properties;
public class Locators {
private static final Properties locators;
static {
locators = new Properties();
InputStream is = Locators.class.getResourceAsStream("/locators.properties");
try {
locators.load(is);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static String getLocator(String locatorName) {
return locators.getProperty(locatorName);
}
}
You would then using it thusly
<pre lang="java">selenium.type(Locators.getLocator("signin.emailbox"), email);
selenium.type(Locators.getLocator("signin.passwordbox"), password);
Which really saves us only 1 character, but..
- The property file loading is done outside of the script
- Because it uses a static block to load things it only actually hits the disk once (when the class is loaded into the jvm)
And both of those I think are worthwhile objectives.
I’m sure that as I get more acquainted with Java I’ll get more of these tricks.