Better manage the Explicit Waits with Selenium WebDriver
This post exists because I had a question on Linkedin when I was sharing the following post that explains about the Implicitly and Explicitly waits: Explicit Wait and Implicit Wait in Selenium: Finally Explained!
I won’t explain the difference because there’re a tons of blog posts and articles about it, but I’ll give you my opinion: only use Explicitly wait.
It’s ok if you don’t know the difference or disagree with my point of view, and I would love to discuss with you on the comment section. ????
Manage different waiting time using Explicitly Wait
Let’s say you have set a global timeout as 5 seconds (for me it’s a plausible waiting time for the test automation scripts. You are using the global timeout in all yours waits but you also have to upload a file, and it can take more than 5 seconds. What you should do?
You can override the wait for this certain element when you are uploading a file without affecting the global timeout using the
withTimeout method only for this specific wait.
On lines 3 and 4 there are the
WebDriverWait attributes declared as global attributes.
The lines 6 to 9 have the pre-condition that will be executed before all the tests using the
@BeforeClass annotation from TestNG. It’s creating the
WebDriver instance using the
ChromeDriver as a browser.
Lines 11 to 14 have the pre-condition for each test using the
@BeforeMethod annotation from TestNG. It will create the
WebDriverWait instance with 5 seconds of a timeout every time a
Line 34 shows the timeout override using the
withTimeout method. It will increase the original timeout defined in the pre-condition for each test.
Line 35 uses the method
withMessage to show a message when the test fails. This helps you to easily understand the exception when it throws.
You can use the code below to run a real example. Please take into consideration this is a didactic example, but it shows a real usage.
Before you use it there’s an explanation: the priority attribute on the annotation
@Test was added to execute the tests in the given numeric order (first the number 1, following by 2 and 3). I do not recommend this approach and I’m using it just to show you an example that I can control.
thisTestWillFail, on lines 41 to 46, will fail because the current timeout is 5 seconds defined in the
beforeEachTest pre-condition method (line 17). But notice that the
thisTestWillPassBecauseOfTheTimeoutOverride, on the lines 43 to 52, will pass because we have increased the timeout for this test.