XPath is used to locate HTML or Mobile elements to perform actions on them or to verify their text. Alternatively, you can use resource ids which are the preferred way to locate elements.
My aim here is to assert equal some description text based on specific xpath depending on another text.
Documents -> You can upload your documents here.
The Xpath contains the word document, and the objective is to check if the text matches.
I decide to use a HashMap in as we're using Appium with Java. Another word to describe this data structure is a dictionary with key value pairs. I store the Xpath text as key and the description text as value. I then iterate through the map, look for the xpath mobile element with the key and assert with the value.
On a side note, the last element has a different XPath than the rest. I therefore also cater for the last one, using an if condition checking the index + 1 equals the map size.
In theory, the logic looks good.
Nevertheless, when running the test, I encounter an error; the last value is never called. To confirm it, I add a log inside of the if condition.
To isolate the error, I start putting printlns everywhere just to understand the flow. I’m always getting the same error - an element is not found.
In the map of three items, the last one behaves different from the first two. So I assume that the Map does not keep the order when iterating. This assumption is reinforced when reading a comment on StackOverflow - stating a HashMap does not keep track of the order.
I assume that this is the issue and start searching online. Instead of using new HashMap, I switch to TreeMap before finalising on LinkedHashMap.
I still got the same exceptions.
I took a break before spending some time reading the library APIs to understand how they iterate values. The way you put the values is the way you will get them when you iterate - unless you sort them, especially true for TreeMap and LinkedHashMap.
Nevertheless, my assumption for the error the whole time is wrong. The code structure is good and working. I’m in fact looking for an element that exists for the first two iterations but not the last one. So by moving it inside of an if statement that checks if it's not the last item, I no longer get this error.