Trixs for maintainable XPaths for test automation - Alternative elements
2024-01-09 (Also published as LinkedIn article)
One of the easiest way of improving web test automation is often to gain better understanding of XPath expressions. One trick is to let the XPath expression itself contain alternative matching strings.
Haven't we all seen (and probably started out with) expressions like these?
These could often be seen to cope with different GUI languages, different versions of the code base, or different test environments.
Sometimes at least the GUI language problems could be mitigated with better focus on testability from the developers, and the different version problem should be a non-problem with good test automation code versioning.
It doesn't get much better using a switch-case statement either, although I probably would prefer it due to code readability. The complexity problems reside.
However, there are always times when different behavior changes the GUI components so you might choose between different element identification strings.
One way of coping with this is with XPath itself by providing alternative identications directly within the XPath expression, like this:
The pipe-symbol (the "|" sign) is used as a logical "OR" operand in many programming languages and in XPath using the pipe-symbol you may state alternative matching patterns. For CSS locators the equivalent is the comma.
As log as there are no other matches for the XPath expression this is a low-maintenance solution that often feel easier to read and understand than complex code selections. Adding new test environments/languages/versions isn't a problem either.
It is worth noting that any XPath expression return a collection of matches. Most test automation tools has methods for using the first match. In Selenium it's FindElement/findElement.