New feature: SofySense – Manual test case & test results AI generator to help you speed up your testing process. Try it today.  

Sofy launches product feature suite to deliver effortless test maintenance and ensure continuous precision – learn more.

sofy logo

Locator Strategy Best Practices

Discover what a locator strategy is, its importance, and how to set up a locator strategy that will help set up your app for automation.

When an engineering team that is currently performing manual testing embarks on test automation whether using scripting or no-code automation, it is important to pay attention to certain characteristics of the app that makes the automation go smoothly.  One of them is element identification, and it’s a reliable way of detecting an element without relying on bound or position coordinates. 

A robust locator strategy is pivotal for creating maintainable and stable automated tests. Below, we’ll delve into the best practices for setting up a locator strategy that serves as the backbone of a successful automated testing process. 

Importance of Establishing a Locator Strategy 

A good locator strategy is paramount in mobile app development, particularly when it involves automated testing. Here’s why it should be a priority: 

  • Reduced likelihood of tests failing due to changes in the UI, enhancing test stability and reliability. 
  • Using locators like IDs and Accessibility IDs creates faster test execution compared to using locators like XPaths. 
  • When the UI changes, you only need to update the locators, improving test maintainability. 
  • Consistent and predictable locators make writing tests less complicated.  
  • Using accessibility locators ensures that the app is more accessible to users with disabilities, which is both a legal and ethical consideration in app development. 

Understanding Your Locators 

The first step in establishing a locator strategy is understanding the locator types available in your testing framework. For instance, Appium, a widely used tool for mobile app testing, provides several locator strategies. 

Accessibility ID 

Accessibility IDs leverage the accessibility identifiers that can be set explicitly by developers. Accessibility IDs are the preferred locator strategy if you’re automating tests cross-platform (iOS and Android), as the same IDs can be used for both. 

Using accessibility locators also ensures that your app is accessible to those with disabilities who rely on screen readers to use your app.  

The accessibility ID for Android is the content-desc element property, while for iOS, it’s the accessibility-id property.  

ID 

Using the ID to find elements is the simplest technique. Each UI element has a unique ID within the app, so you can use these identifiers to locate and interact with each element within the app.  

An element’s ID is stored either in the resource-id on Android or the name attribute on iOS. 

XPath 

XPath analyzes an app’s XML hierarchy and locates the desired element. Using XPaths as a locator strategy is not typically recommended, however, due to its stability issues and slower performance. XPath should only be used when no other locator strategies will work.   

Class Name 

You can use class names for locating elements based on their UI class. Class name is useful when you want to identify a group of elements, or for finding elements when ID or Name are not available. Because multiple elements may have the same class name, it’s recommended you use the class name with other locators if you want to locate a specific element.  

In Android, you can locate an element by its class using the className locator. For iOS, the XCTest framework allows you to locate elements by their UI class types, like XCUIElementTypeButton for buttons. 

Android UI Automator 2 

This locator is Android-specific and is a powerful tool to construct a query to find elements. To use this locator, you must also use the UI Automator API (specifically, the UISelector Class), so knowledge of this API is required. The UISelector specifies the elements in the layout hierarchy for tests to target, filtered by properties such as text value, content-description, class name, and state information 

iOS XCUITest 

This locator is iOS-specific and uses Apple’s XCTest framework to locate elements while automating tests. XCUITest interacts with the app’s user interface by locating UI elements and then performing actions or checking the element’s properties. Locators in the context of XCUITest are queries used to find these UI elements in the application’s accessibility hierarchy. 

Best Practices for Setting up a Locator Strategy 

1. Prefer Accessibility IDs 

Accessibility IDs are not only beneficial for users with accessibility needs but also serve as stable locators for automated tests. When using Accessibility IDs, follow these best practices:  

  • Ensure that each interactive element on the screen has a unique Accessibility ID. This prevents confusion during testing and also aids users who rely on screen readers. 
  • Testers should collaborate with developers from the beginning to establish the use of Accessibility IDs. Developers need to implement these IDs in the app’s code, so it’s essential to make this a part of the development process. 
  • Accessibility IDs should be descriptive and meaningful. They should indicate the element’s purpose or content, which is helpful for both testers and users utilizing accessibility features. 

Example: Testing a ‘Login’ Feature in a Mobile App 

 

Imagine you’re automating tests for a mobile app with a login feature. The login screen has a username field, a password field, and a login button. 

Developers can assign accessibility IDs such as loginUsername, loginPassword, and loginButton to these elements. In your test scripts, you can directly use these IDs to locate and interact with these elements, like entering text in the username and password fields and clicking the login button. 

Accessibility IDs are typically stable and unique to each element. Even if the layout or design of the login screen changes (e.g., the fields are rearranged, or the style is updated), the accessibility IDs remain the same, ensuring that your tests continue to work without any modifications. 

In contrast, if you were using XPath or CSS selectors, even minor UI changes could break your tests. For example, an XPath relying on the position of the elements (e.g., //android.widget.EditText[1]) would fail if an additional input field were added to the form. 

Class names might not be unique or could be reused on different elements, leading to less reliable tests. 

IDs other than accessibility IDs, can sometimes be dynamically generated, especially in web applications, leading to inconsistencies across different environments or app versions. 

2. Use IDs Over XPath 

Native IDs (resource-id for Android and name for iOS) are faster and more reliable compared to XPath. As mentioned before, XPath is typically not recommended due to its stability issues and slower performance, so you should only use XPath when no other locator will work.  

Encourage developers to provide unique IDs for elements during the development process. Some best practices for using IDs include: 

  • Use concise and descriptive names for each ID. For example, loginButton is better than button1. 
  • Follow consistent naming conventions across your entire app. For example, you can use the convention activityName_elementType_purpose, such as mainActivity_button_login. 
  • Avoid duplicate IDs when possible. Use unique IDs within each file type, although in Android, you can use the same ID in different layouts if they are part of different activities or fragments. 

Example: Locating a Login Button 

 

Suppose you have a login button that needs to be located for automation testing purposes. An XPath expression might look something like this (on Android): //android.widget.LinearLayout[3]/android.widget.FrameLayout[1]/android.widget.EditText[4]. This XPath locator is based on the XML structure.  

The problem with using XPaths is that if there are any changes in the XML structure (like if a new input field is added before the login button), the XPath will no longer correctly locate the button, resulting in a test failure.  

However, if the login button has an ID, such as id=”loginButton”, you can simply use this ID to locate the element. IDs are unique to each element, and the likelihood of an ID changing is much lower compared to the XML structure. Even if the structure of the page changes, the ID will remain the same, and your locator will still work. 

3. Avoid Flaky XPath Locators 

If XPath is necessary, avoid using XPath locators that rely on the position or full path, as these can break with UI changes. Instead, use relative paths and specific attributes that are less likely to change, and keep XPath expressions short and straightforward.  

Note that XPath on iOS runs significantly slower than on Android, so if you’re writing cross-platform tests, it’s best to use different locator strategies for iOS and Android if you’re intending to use XPath locators.  

Example: Locating a ‘Submit’ Button in a Mobile App 

Imagine you are automating tests for a mobile banking app, and you need to locate a ‘Submit’ button on the funds transfer screen. 

A full XPath to this button might look like: /hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.Button[3]. The problem with this approach is its fragility. If any part of the UI hierarchy changes — such as a new layout being added or an existing one being removed — the XPath will no longer correctly locate the button. Even a minor UI tweak could render the test useless. 

A relative XPath, in comparison, could be something like: //android.widget.Button[@content-desc=’Submit’]. This XPath does not rely on the complete path from the root. Instead, it searches for any Button element throughout the UI that has a content-desc (content description) of ‘Submit’. The relative XPath remains valid even if the UI layout changes, as long as the ‘Submit’ button still exists and retains the same content-desc. 

4. Abstract Locators 

Locator changes should not lead to massive code changes. You can use the Page Object Model (POM) to encapsulate locators and interactions with them. POM is a design pattern and serves as an abstraction layer between the test scripts and the page layouts, leading to cleaner, more maintainable, and reusable code. With POM, you only need to update the locators or interactions in one place within the page object, rather than throughout all test scripts. 

Here are some best practices for using the Page Object Model:  

  • Define UI element locators and interactions within page objects, rather than directly in the test scripts.  
  • Stick to a single page object per page or logical unit of the application. If a page is complex, consider breaking it down into components or sections that are represented by separate classes, which can then be used within the page object. 
  • The internal structure of the page should be hidden from tests. Methods in the page object should represent high-level interactions such as loginAs(user) rather than exposing implementation details like input fields and buttons. 

Example: Testing a Mobile Shopping App 

 

Suppose you’re tasked with automating tests for a mobile shopping app. Your test involves verifying the functionality of the product search feature. 

Without the Page Object Model (POM), your test scripts will directly interact with the app’s UI elements. They include specific locators like: ‘driver.findElement(By.id(“searchField”))’ and ‘driver.findElement(By.id(“submitButton”))’. If the UI changes (e.g., the ID of the search field or submit button changes), you need to go through all the test scripts to update these locators. This approach is time-consuming and prone to errors. 

With the Page Object Model, you can create a SearchPage class representing the search functionality of the app. Inside this class, you can encapsulate the locators and methods for interactions, such as entering text into the search field and clicking the submit button. The test scripts then interact with instances of the SearchPage class, not directly with the UI elements. 

With the POM, updates to UI elements (like changing IDs) only require changes in the page object class, not across multiple test scripts. They can also be reused across different tests that involve product search functionality. 

5. Collaborate with Developers 

Ensuring elements are easily identifiable can sometimes require changes in the app’s code. QA and developers should engage in collaborative discussions to establish conventions for IDs and accessibility attributes, and implement a locator dictionary that both developers and QA can access.  

6. Centralize Locator Management 

Changes to locators should be easy to manage and update. An easy way to manage your locators is by storing them in a single file or a set of constants that can be reused across tests. 

7. Avoid Overlapping Locators 

Unique identifiers for each element prevent the risk of interacting with the wrong element. You can automate checks as part of your CI/CD pipeline that can detect duplicate locators. 

Following other unique ID best practices, like using a consistent naming convention and unique identifiers, will also help prevent overlapping locators.  

Finally, construct locators that are both hierarchical and descriptive. Hierarchical locators show the relationship to the parent or surrounding elements, which can help distinguish elements that might otherwise have overlapping locators. 

8. Test Your Locators 

Verifying that locators are effective and efficient ensures stability in your tests. To do this, periodically run sanity checks that solely test the presence and responsiveness of elements using your locators.  

With Sofy, you can compare recordings of your automated tests with the original recording and use the Element Explorer to verify that the system is locating your elements properly. If an automated test has failed, the Element Explorer will help you identify if it’s an issue with your app UI element’s locators.   

Some things to look for when testing your locators: 

  • Locators only return one element (unless you are using a locator to return multiple elements). 
  • Locators work across different devices and screens. 
  • Locators perform as expected under different app states. 

9. Document Your Strategy 

Consistency across the testing team is key to a manageable test suite. To better manage your locator strategy, create a guide that defines the types of locators to use in various scenarios and share it with your team. Create naming conventions and use unique identifiers for locator types like IDs to ensure consistency across the app.  

10. Stay Adaptable 

As the app evolves, your locator strategy may need to evolve too. Regularly revisit and revise the locator strategy to accommodate new features and UI changes. Engage in peer reviews by having team members review locators and associated tests. Fresh eyes may catch issues that the original author did not. 

Conclusion 

Setting up an effective locator strategy is not a one-time task—it’s an ongoing process of collaboration, refinement, and adaptation. By following these best practices, mobile app developers and QA testers can create a robust foundation for automated tests, resulting in faster development cycles, higher-quality apps, and a smoother user experience. Remember, the strength of your automated tests lies in the reliability of your locators. Keep them precise, keep them efficient, and your path to successful automation will be significantly smoother. 

Discover how visual validation testing can help developers and QA testers identify and fix visual bugs before they’re released to production.