Search form

Randomness is the Key!

Explicit Wait with Selenium

Submitted by dimaj on Sun, 12/14/2014 - 00:32

Recently I started working with Appium for testing our mobile applications. Since we are developing applications for both Android and iOS, Appium seemed like a logical choice. To make my automation more effective, I have decided to write my own element search mechanism that would allow user to specify element search methods in a predefined order. Here's a small sample of how it works:

Sadly this approach proved to be very ineffective and my search was running a lot longer than what I expected. Then, after doing more research on waits with Selenium WebDriver, I stumbled upon Explicit Waits.

In a word, here's how it works:
You specify a condition and Explicit Wait mechanism is going to run until your condition either met or your specified timeout expires (in which case you'll end up with a TimeoutException). There are couple of ways you can use explicit waits with Selenium:
Using an ExpetedCondition interface or building out your own mechanism.

First, let's cover the ExpectedCondition. Off the shelf, selenium comes with bunch of predefined conditions such as titleContains, elementToBeClickable, etc. You can get a comprehensive list by visiting selenium's API docs: here.
An example of this approach would look something like this:

Second solution would be to create your own mechanism. Again, this could be done in at least 2 ways: just like the second example of the first approach and using a final variable and use it in the apply method.

Now, let's look at the code above in more detail:
On line 1, I am creating a new FluentWait object that is going to do something until my timeout expires. Then, in the try/catch block, I am creating a new Function object that is going to perform an action until action's return value is not null or timeout expires. In my case, the action to be performed comes from a class ElementSearcher which has a method called runSearch (which is a re-write of my original approach above).

The performance with this approach is great! Timeouts work very well and my automated scripts are running much faster!