In Selenium, creating an object repository is an effective method to improve the maintainability and reusability of automation test scripts. An object repository is a dedicated storage area for storing all UI element locators (e.g., ID, Name, XPath, etc.), which avoids hardcoding these locators in automation scripts. Below, I will detail how to create and use an object repository in Selenium.
1. Defining the Object Repository Structure
First, we need to decide on the storage format for the object repository. Common formats include:
- Excel file
- XML file
- Properties file
Choose the appropriate format based on project requirements and team preferences. For example, if the team is accustomed to using Excel, an Excel file can be selected to store the element locators.
2. Creating the Object Repository File
Assuming we choose a Properties file as the object repository, we can create a file named elements.properties and store the element locators within it, such as:
propertiesloginButton = id:login-button usernameField = xpath://input[@id='username'] passwordField = css:input[name='password']
3. Reading the Object Repository
In Selenium test scripts, we need to read the locators from the object repository file. This can be achieved using Java's Properties class. For example:
javaProperties props = new Properties(); FileInputStream in = new FileInputStream("path/to/elements.properties"); props.load(in); in.close(); // Using the locator driver.findElement(By.id(props.getProperty("loginButton"))).click();
4. Implementing Encapsulation
To enhance code maintainability and reusability, we can encapsulate a utility class or method to handle the reading of the object repository and element location. For example, create an ElementLocator class:
javapublic class ElementLocator { private static Properties props; static { props = new Properties(); try (FileInputStream in = new FileInputStream("path/to/elements.properties")) { props.load(in); } catch (IOException e) { e.printStackTrace(); } } public static By getLocator(String key) { String value = props.getProperty(key); String[] parts = value.split(":", 2); switch (parts[0]) { case "id": return By.id(parts[1]); case "xpath": return By.xpath(parts[1]); case "css": return By.cssSelector(parts[1]); default: throw new IllegalArgumentException("Locator type not supported: " + parts[0]); } } }
5. Using the Encapsulated Method
In test scripts, we can use the ElementLocator.getLocator method to retrieve the locator:
javadriver.findElement(ElementLocator.getLocator("loginButton")).click();
Conclusion
By doing this, we can centrally manage the UI element locators, requiring only a single update in one place when elements change, which improves the maintainability and reusability of test code. Additionally, this approach enhances collaboration among team members.