Create an object repository for Selenium WebDriver

Posted on Updated on

Problem

It is very useful to extract the locators from the test code. This makes your test code much more maintainable and readable. Beside of that there is no need to recompile the project after changing the identifiers. There are many ways to do it, but we will see just one way in this example. It can be done by the Java properties file. Just load the file in front of running the tests and then you can use all the properties, that is basically everything what you have to do. The properties file is just flat text. That is why there is no need to recompile the whole source code once locators have been changed. We can also make use of the same locators in multiple test cases. These are big advantages of using a object repository.

Prerequisites

We can install Eclipse as preferred IDE to setup a Java test project.

Solution

  1. We have to create a properties file, given this name locators.properties. The part before the equals sign is the key, the part after the equals sign is the value. We can give the following content to the file:
1
2
login.username.textfield=css=input#username
login.password.textfield=css=input#password
  1. We have to load the properties file, before we can call the locators. We have to initiate the properties object and load the contents of the file in it. We can do this with the following code:
1
2
3
4
5
6
Properties props = new Properties();
try {
    InputStream in = getClass().getResourceAsStream("locators.properties");
    props.load(in);
} catch (IOException e) {
}
  1. We can use the object repository, once the key/values are actually loaded in the properties object. We can use the value in our tests, by calling the key parameter, like this:
1
props.getProperty("login.username.textfield")

What has been done

We are loading a key/value pairs into a properties object. Make sure you will do this in front of running any tests. Finally we are able to get the value by it’s key.

Source Code

The source code is available on GitHub at the following location: https://github.com/roydekleijn/HowToUsePropertiesFile

– See more at: http://selenium.polteq.com/en/category/tips-tricks/#sthash.G7LIVZco.dpuf

Leave a comment