SlideShare a Scribd company logo
1 of 42
Java. Explicit and Implicit Wait.
Testing Ajax Applications
IT Academy
24/03/2015
Agenda
▪Implicit Wait
▪Explicit Wait
▪Taking a Screenshot
▪Ajax Applications
▪Testing Ajax Applications
▪Examples
▪Case studies
Explicit and Implicit Wait
Explicit/Implicit Waits
▪ Explicit and Implicit Waits
– Waiting is having the automated task execution elapse a
certain amount of time before continuing with the next
step.
▪ Explicit Waits
– An explicit waits is code you define to wait for a certain
condition to occur before proceeding further in the code.
– The worst case of this is Thread.sleep();
Explicit/Implicit Waits
@Test
public void testSearchTC() throws Exception {
driver.get("https://www.google.com.ua/");
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("selenium ide");
driver.findElement(By.id("gbqfb")).click();
Thread.sleep(1000);
driver.findElement(By
.xpath("//ol[@id='rso']/div/li[2]/div/h3/a/em")).click();
assertEquals("Selenium IDE is a Firefox plugin … for any
kind of resiliency.", driver.findElement(By
.xpath("//div[@id='mainContent']/p[2]")).getText());
} }
Explicit/Implicit Waits
▪ Implicit Waits
– An implicit wait is to tell WebDriver to poll the DOM for a
certain amount of time when trying to find an element or
elements if they are not immediately available.
– The default setting is 0.
– Once set, the implicit wait is set for the life of the
WebDriver object instance.
Explicit/Implicit Waits
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
Explicit/Implicit Waits
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
Explicit/Implicit Waits
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
} } );
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
// Close the browser
driver.quit();
} }
WebDriverWait
▪ Anonymous classes enable you to make your code more
concise.
▪ They enable you to declare and instantiate a class at the same
time.
▪ They are like local classes except that they do not have a
name.
▪ Use them if you need to use a local class only once.
(new WebDriverWait(driver, 10)).until(new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
} } );
WebDriverWait
▪ This is equivalent to:
class MyExpectedCondition
extends ExpectedCondition<Boolean> {
public Boolean apply(WebDriver d) {
return d.getTitle( ).toLowerCase( ).startsWith("cheese!");
}
}
MyExpectedCondition my = new MyExpectedCondition();
WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(my);
Explicit Waits
▪ There are some convenience methods provided that help you
write code that will wait only as long as required.
▪ WebDriverWait in combination with ExpectedCondition is
one way this can be accomplished.
WebDriver driver = new FirefoxDriver();
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement =
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.id("myDynamicElement")));
Explicit Waits
WebElement myDynamicElement =
(new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.id("myDynamicElement")));
▪ This waits up to 10 seconds before throwing a
TimeoutException or if it finds the element will return it in 0 –
10 seconds.
▪ WebDriverWait by default calls the ExpectedCondition every
500 milliseconds until it returns successfully.
▪ A successful return is for ExpectedCondition type is Boolean
return true or not null return value for all other
ExpectedCondition types.
Explicit Waits
▪ Java to have convienence methods so you don’t have to code
an ExpectedCondition class yourself or create your own
utility package for them.
▪ Element is Clickable – it is Displayed and Enabled
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(
By.id("someid")));
Implicit Waits
▪ An implicit wait is to tell WebDriver to poll the DOM for a
certain amount of time when trying to find an element or
elements if they are not immediately available. The default
setting is 0.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement =
driver.findElement(By.id("myDynamicElement"));
WebDriver Wait Commands
▪ Listing out the different WebDriver Wait statements that can
be useful for an effective scripting and can avoid using the
Thread.sleep() comamnds.
WebDriver Wait Commands
WebDriver Wait
▪ implicitlyWait
▪ The ImplicitWait will tell the webDriver to poll the DOM for a
certain duration when trying to find the element, this will be
useful when certain elements on the webpage will not be
available immediately and needs some time to load.
▪ By default it ill take the value to 0, for the life of the WebDriver
object instance through out the test script.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10,
TimeUnit.SECONDS);
driver.get("http://somedomain/url_that_delays_loading");
WebElement myDynamicElement =
driver.findElement(By.id("myDynamicElement"));
WebDriver Wait. Timeout
▪ pageLoadTimeout
– Sets the amount of time to wait for a page load to
complete before throwing an error.
– If the timeout is negative, page loads can be indefinite.
driver.manage().timeouts().pageLoadTimeout(100, SECONDS);
▪ setScriptTimeout
– Sets the amount of time to wait for an asynchronous script
to finish execution before throwing an error.
– If the timeout is negative, then the script will be allowed to
run indefinitely.
driver.manage().timeouts().setScriptTimeout(100,SECONDS);
WebDriver Wait
▪ FluentWait
▪ Each FluentWait instance defines the maximum amount of
time to wait for a condition, as well as the frequency with
which to check the condition.
▪ Furthermore, the user may configure the wait to ignore
specific types of exceptions whilst waiting, such as
NoSuchElementExceptions when searching for an
element on the page.
WebDriver Wait
// Waiting 30 seconds for an element to be present on the
// page, checking for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, SECONDS)
.pollingEvery(5, SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver,
WebElement>() {
public WebElement apply(WebDriver driver) {
return driver.findElement(By.id("foo"));
}
} );
WebDriver Wait Commands
▪ ExpectedConditions
▪ Would include determining if a web page has loaded or that
an element is visible.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(
By.id("someid")));
▪ WebDriverWait will be used as we used in the Expected
conditions code snippet as above.
▪ Sleeper is something same as the Thread.sleep() method.
Waits Solution
long implicitlyWaitTimeout = 10;
public long getImplicitlyWaitTimeout() {
return implicitlyWaitTimeout;
}
public WebDriver getWebDriver() {
driver = new FirefoxDriver();
driver.manage().timeouts()
.implicitlyWait(getImplicitlyWaitTimeout(),
TimeUnit.SECONDS);
driver.manage().window().maximize();
return driver;
}
Waits Solution
public WebElement getWebElement(String name) {
WebElement webElement = new WebDriverWait(
getWebDriver(),
getImplicitlyWaitTimeout())
.until(ExpectedConditions
.visibilityOfElementLocated(By.name(name));
if (webElement == null) {
throw new RuntimeException("My Error");
}
return webElement;
}
Taking a Screenshot
Taking a Screenshot
▪ Most of the time we think to Capture Screenshot in WebDriver
when some kind of error or exception surfaces while practicing
testing, to resolve the same WebDriver has provided us one
interface TakesScreenshot for capturing the screenshot of
web application and This interface provides one method
names as getScreenshotAs() to capture screenshot in
instance of driver.
▪ This getScreenshotAs() method takes argument of type
OutputType.File or OutputType.BASE64 or
Output.BYTES.
Taking a Screenshot
▪ We have taken the screenshot with the help of
getScreenshotsAs() method and and now its time to
copy this file somewhere in our file system.
▪ So for this purpose we further use copyFile() method of
the FileUtils class from the
org.apache.commons.io.FileUtils class.
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com.ua/");
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// For example copy somewhere
FileUtils.copyFile(scrFile, new File("c:tmpscreenshot.png"));
Taking a Screenshot
▪ Take the screenshot in the @After test tear down method,
which is run after every test.
▪ This way you will always get a screenshot for both passed and
failed tests.
public class TestSample {
WebDriver driver;
@Before
public void setUp() {
// Start new webdriver session, for eg using firefox
driver = new FirefoxDriver();
}
Taking a Screenshot
@Test
public void aTest() {
driver.get("http://www.google.com.ua/");
// more test logic - test might pass or fail at this point }
@After
public void tearDown() {
// take the screenshot at the end of every test
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// now save the screenshto to a file some place
FileUtils.copyFile(scrFile, new File("c:tmpscreenshot.png"));
driver.quit(); } }
Taking a Screenshot
try {
File scrnsht =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrnsht, new File("e:google_page.png"));
} catch (Exception e) {
e.printStackTrace();
}
Testing Ajax Applications
with Selenium
Testing Ajax Applications
▪ Many web applications contain AJAX calls.
– AJAX calls don’t refresh the whole page, only a certain part
of a page is refreshed.
– When an AJAX call is made, while the page is waiting for a
response from the server, a waiting icon appears on the
page to inform the user, the page is waiting for
information, this could be either a rotating circle, or a
loading horizontal bar, etc.
▪ WebDriver is clever enough to wait for the whole page to load
before doing any action and without the user having to
specify a wait for page to load.
– However, in case of AJAX calls, because the whole page is
not refreshed, WebDriver has no way of knowing
something is happening.
Testing Ajax Applications
▪ http://www.w3schools.com/ajax/default.asp
Testing Ajax Applications
Testing Ajax Applications
▪ In AJAX driven web applications, data is retrieved from server
without refreshing the page.
– Using and Wait commands will not work as the page is not
actually refreshed.
– Pausing the test execution for a certain period of time is
also not a good approach as web element might appear
later or earlier than the stipulated period depending on
the system’s responsiveness, load or other uncontrolled
factors of the moment, leading to test failures.
▪ The best approach would be to wait for the needed element in
a dynamic period and then continue the execution as soon as
the element is found.
Testing Ajax Applications
▪ This is done using waitFor commands, as
waitForElementPresent or waitForVisible, which wait
dynamically, checking for the desired condition every second
and continuing to the next command in the script as soon as
the condition is met.
▪ The best practice is to set implicitlyWait() at the
beginning of each test, and use WebDriverWait() for
waiting an element, or AJAX element to load.
Testing Ajax Applications
▪ However, implicitlyWait() and WebDriverWait() do
not work well together in the same test.
▪ You would have to nullify implicitlyWait() before calling
WebDriverWait because implicitlyWait() also sets the
"driver.findElement()" wait time.
▪ For Example, develop WaitTool. It solves the complexity of
ImplicitWait and WebDriverWait, and provides easy methods
to use.
Testing Ajax Applications
▪ WaitTool handles the following tasks at the behind scene.
– nullifying implicitlyWait();
– executing WebDriverWait(), and return element;
– reset implicitlyWait() again.
Testing Ajax Applications
public static void waitForElementPresent(WebDriver driver,
final By by, int timeOutInSecond) {
try {
// nullify implicitlyWait()
driver.manage().timeouts()
.implicitlyWait(0, TimeUnit.SECONDS);
// Create web element
WebElement webElement =
new WebDriverWait(driver, timeOutInSecond)
Testing Ajax Applications
WebElement webElement =
new WebDriverWait(driver, timeOutInSecond)
.until(new
ExpectedConditions<Boolean>() {
@Overridew
public Boolean apply(WebDriver d) {
return isElementPresent(d, by);
} } );
// reset implicitlyWait()
driver.manage().timeouts()
.implicitlyWait(10, TimeUnit.SECONDS);
} catch(Exceptions e) { …
References
▪ Explicit and Implicit Waits
http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp
▪ Selenium WebDriver
http://docs.seleniumhq.org/docs/03_webdriver.jsp
▪ How to Handle Ajax call in Selenium Webdriver
http://agilesoftwaretesting.com/selenium-wait-for-ajax-the-right-
Java. Explicit and Implicit Wait. Testing Ajax Applications

More Related Content

What's hot

Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Frameworkvaluebound
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...Simplilearn
 
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...Edureka!
 
Introduction To Mobile-Automation
Introduction To Mobile-AutomationIntroduction To Mobile-Automation
Introduction To Mobile-AutomationMindfire Solutions
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedStéphane Bégaudeau
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Frameworklaurent bristiel
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Edureka!
 
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...Edureka!
 
Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Zhe Li
 
Different wait methods or commands in Selenium
Different wait methods or commands in SeleniumDifferent wait methods or commands in Selenium
Different wait methods or commands in SeleniumVinay Kumar Pulabaigari
 
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...CSS Grid Layout. Specification overview. Implementation status and roadmap (B...
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...Igalia
 

What's hot (20)

Setting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation FrameworkSetting up Page Object Model in Automation Framework
Setting up Page Object Model in Automation Framework
 
Selenium presentation
Selenium presentationSelenium presentation
Selenium presentation
 
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
What Is Selenium? | Selenium Basics For Beginners | Introduction To Selenium ...
 
Selenium Primer
Selenium PrimerSelenium Primer
Selenium Primer
 
Selenium
SeleniumSelenium
Selenium
 
Test automation proposal
Test automation proposalTest automation proposal
Test automation proposal
 
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...
Selenium WebDriver Tutorial For Beginners | What Is Selenium WebDriver | Sele...
 
Selenium WebDriver training
Selenium WebDriver trainingSelenium WebDriver training
Selenium WebDriver training
 
Mern stack developement
Mern stack developementMern stack developement
Mern stack developement
 
Introduction To Mobile-Automation
Introduction To Mobile-AutomationIntroduction To Mobile-Automation
Introduction To Mobile-Automation
 
AngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get startedAngularJS 101 - Everything you need to know to get started
AngularJS 101 - Everything you need to know to get started
 
Functional Tests Automation with Robot Framework
Functional Tests Automation with Robot FrameworkFunctional Tests Automation with Robot Framework
Functional Tests Automation with Robot Framework
 
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
Selenium Tutorial For Beginners | What Is Selenium? | Selenium Automation Tes...
 
Selenium Automation Framework
Selenium Automation  FrameworkSelenium Automation  Framework
Selenium Automation Framework
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
Selenium Interview Questions and Answers | Selenium Tutorial | Selenium Train...
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Introduction to Robot Framework (external)
Introduction to Robot Framework (external)Introduction to Robot Framework (external)
Introduction to Robot Framework (external)
 
Different wait methods or commands in Selenium
Different wait methods or commands in SeleniumDifferent wait methods or commands in Selenium
Different wait methods or commands in Selenium
 
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...CSS Grid Layout. Specification overview. Implementation status and roadmap (B...
CSS Grid Layout. Specification overview. Implementation status and roadmap (B...
 

Viewers also liked

Selenium with C# and Java Titbits
Selenium with C# and Java TitbitsSelenium with C# and Java Titbits
Selenium with C# and Java Titbitsayman diab
 
Kusuma_Resume_5+
Kusuma_Resume_5+Kusuma_Resume_5+
Kusuma_Resume_5+kusuma T
 
Getting started with_testcomplete
Getting started with_testcompleteGetting started with_testcomplete
Getting started with_testcompleteankit.das
 
Selenium WebDriver: Tips and Tricks
Selenium WebDriver: Tips and TricksSelenium WebDriver: Tips and Tricks
Selenium WebDriver: Tips and TricksEdureka!
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questionsShivaraj R
 
Test Driven Development (C#)
Test Driven Development (C#)Test Driven Development (C#)
Test Driven Development (C#)Alan Dean
 
Selenium_WebDriver_Java_TestNG
Selenium_WebDriver_Java_TestNGSelenium_WebDriver_Java_TestNG
Selenium_WebDriver_Java_TestNGBasul Asahab
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Roy de Kleijn
 
Testing with test_complete
Testing with test_completeTesting with test_complete
Testing with test_completebinuiweb
 
Keyword Driven Testing using TestComplete
Keyword Driven Testing using TestCompleteKeyword Driven Testing using TestComplete
Keyword Driven Testing using TestCompletesrivinayak
 
Exactpro Test Tools EXTENT Feb 2011
Exactpro Test Tools EXTENT Feb 2011Exactpro Test Tools EXTENT Feb 2011
Exactpro Test Tools EXTENT Feb 2011Iosif Itkin
 
Automation Testing with TestComplete
Automation Testing with TestCompleteAutomation Testing with TestComplete
Automation Testing with TestCompleteRomSoft SRL
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instrumentsArtem Nagornyi
 
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearTestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearSoftware Testing Solution
 
Technical Testing Introduction
Technical Testing IntroductionTechnical Testing Introduction
Technical Testing IntroductionIosif Itkin
 
Selenium Webdriver Interview Questions
Selenium Webdriver Interview QuestionsSelenium Webdriver Interview Questions
Selenium Webdriver Interview QuestionsJai Singh
 
Software Quality Assurance Engineer_Lenin_Resume
Software Quality Assurance Engineer_Lenin_ResumeSoftware Quality Assurance Engineer_Lenin_Resume
Software Quality Assurance Engineer_Lenin_ResumeLenin MS
 

Viewers also liked (20)

Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
Selenium with C# and Java Titbits
Selenium with C# and Java TitbitsSelenium with C# and Java Titbits
Selenium with C# and Java Titbits
 
Kusuma_Resume_5+
Kusuma_Resume_5+Kusuma_Resume_5+
Kusuma_Resume_5+
 
Getting started with_testcomplete
Getting started with_testcompleteGetting started with_testcomplete
Getting started with_testcomplete
 
Selenium WebDriver: Tips and Tricks
Selenium WebDriver: Tips and TricksSelenium WebDriver: Tips and Tricks
Selenium WebDriver: Tips and Tricks
 
Cucumber questions
Cucumber questionsCucumber questions
Cucumber questions
 
Test Driven Development (C#)
Test Driven Development (C#)Test Driven Development (C#)
Test Driven Development (C#)
 
Selenium_WebDriver_Java_TestNG
Selenium_WebDriver_Java_TestNGSelenium_WebDriver_Java_TestNG
Selenium_WebDriver_Java_TestNG
 
Beyond Page Objects
Beyond Page ObjectsBeyond Page Objects
Beyond Page Objects
 
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016Improving Your Selenium WebDriver Tests - Belgium testing days_2016
Improving Your Selenium WebDriver Tests - Belgium testing days_2016
 
Testing with test_complete
Testing with test_completeTesting with test_complete
Testing with test_complete
 
Keyword Driven Testing using TestComplete
Keyword Driven Testing using TestCompleteKeyword Driven Testing using TestComplete
Keyword Driven Testing using TestComplete
 
Exactpro Test Tools EXTENT Feb 2011
Exactpro Test Tools EXTENT Feb 2011Exactpro Test Tools EXTENT Feb 2011
Exactpro Test Tools EXTENT Feb 2011
 
Automation Testing with TestComplete
Automation Testing with TestCompleteAutomation Testing with TestComplete
Automation Testing with TestComplete
 
Web UI test automation instruments
Web UI test automation instrumentsWeb UI test automation instruments
Web UI test automation instruments
 
Testing_with_TestComplete
Testing_with_TestCompleteTesting_with_TestComplete
Testing_with_TestComplete
 
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBearTestComplete – A Sophisticated Automated Testing Tool by SmartBear
TestComplete – A Sophisticated Automated Testing Tool by SmartBear
 
Technical Testing Introduction
Technical Testing IntroductionTechnical Testing Introduction
Technical Testing Introduction
 
Selenium Webdriver Interview Questions
Selenium Webdriver Interview QuestionsSelenium Webdriver Interview Questions
Selenium Webdriver Interview Questions
 
Software Quality Assurance Engineer_Lenin_Resume
Software Quality Assurance Engineer_Lenin_ResumeSoftware Quality Assurance Engineer_Lenin_Resume
Software Quality Assurance Engineer_Lenin_Resume
 

Similar to Java. Explicit and Implicit Wait. Testing Ajax Applications

Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationRichard North
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideMek Srunyu Stittri
 
Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questionsarchana singh
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest servicesIoan Eugen Stan
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serializationGWTcon
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testingdrewz lin
 
Gilt Groupe's Selenium 2 Conversion Challenges
Gilt Groupe's Selenium 2 Conversion ChallengesGilt Groupe's Selenium 2 Conversion Challenges
Gilt Groupe's Selenium 2 Conversion ChallengesSauce Labs
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojosdeconf
 
Component Based Unit Testing ADF with Selenium
Component Based Unit Testing ADF with SeleniumComponent Based Unit Testing ADF with Selenium
Component Based Unit Testing ADF with SeleniumRichard Olrichs
 
Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법Minchul Jung
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++Amazon Web Services
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Get Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 GridGet Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 GridDaniel Herken
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 

Similar to Java. Explicit and Implicit Wait. Testing Ajax Applications (20)

Web driver training
Web driver trainingWeb driver training
Web driver training
 
Testcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentationTestcontainers - Geekout EE 2017 presentation
Testcontainers - Geekout EE 2017 presentation
 
Node.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java sideNode.js and Selenium Webdriver, a journey from the Java side
Node.js and Selenium Webdriver, a journey from the Java side
 
Experienced Selenium Interview questions
Experienced Selenium Interview questionsExperienced Selenium Interview questions
Experienced Selenium Interview questions
 
Javascript ui for rest services
Javascript ui for rest servicesJavascript ui for rest services
Javascript ui for rest services
 
WebDriver Waits
WebDriver WaitsWebDriver Waits
WebDriver Waits
 
Automated testing by Richard Olrichs and Wilfred vd Deijl
Automated testing by Richard Olrichs and Wilfred vd DeijlAutomated testing by Richard Olrichs and Wilfred vd Deijl
Automated testing by Richard Olrichs and Wilfred vd Deijl
 
GWT Web Socket and data serialization
GWT Web Socket and data serializationGWT Web Socket and data serialization
GWT Web Socket and data serialization
 
Top100summit 谷歌-scott-improve your automated web application testing
Top100summit  谷歌-scott-improve your automated web application testingTop100summit  谷歌-scott-improve your automated web application testing
Top100summit 谷歌-scott-improve your automated web application testing
 
Gilt Groupe's Selenium 2 Conversion Challenges
Gilt Groupe's Selenium 2 Conversion ChallengesGilt Groupe's Selenium 2 Conversion Challenges
Gilt Groupe's Selenium 2 Conversion Challenges
 
Webdriver.io
Webdriver.io Webdriver.io
Webdriver.io
 
C fowler azure-dojo
C fowler azure-dojoC fowler azure-dojo
C fowler azure-dojo
 
Web ui testing
Web ui testingWeb ui testing
Web ui testing
 
Component Based Unit Testing ADF with Selenium
Component Based Unit Testing ADF with SeleniumComponent Based Unit Testing ADF with Selenium
Component Based Unit Testing ADF with Selenium
 
Automated Testing ADF with Selenium
Automated Testing ADF with SeleniumAutomated Testing ADF with Selenium
Automated Testing ADF with Selenium
 
Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법Ch10.애플리케이션 서버의 병목_발견_방법
Ch10.애플리케이션 서버의 병목_발견_방법
 
(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++(DEV204) Building High-Performance Native Cloud Apps In C++
(DEV204) Building High-Performance Native Cloud Apps In C++
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Get Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 GridGet Started With Selenium 3 and Selenium 3 Grid
Get Started With Selenium 3 and Selenium 3 Grid
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 

Recently uploaded

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Recently uploaded (20)

How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Java. Explicit and Implicit Wait. Testing Ajax Applications

  • 1. Java. Explicit and Implicit Wait. Testing Ajax Applications IT Academy 24/03/2015
  • 2. Agenda ▪Implicit Wait ▪Explicit Wait ▪Taking a Screenshot ▪Ajax Applications ▪Testing Ajax Applications ▪Examples ▪Case studies
  • 4. Explicit/Implicit Waits ▪ Explicit and Implicit Waits – Waiting is having the automated task execution elapse a certain amount of time before continuing with the next step. ▪ Explicit Waits – An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. – The worst case of this is Thread.sleep();
  • 5. Explicit/Implicit Waits @Test public void testSearchTC() throws Exception { driver.get("https://www.google.com.ua/"); driver.findElement(By.id("gbqfq")).clear(); driver.findElement(By.id("gbqfq")).sendKeys("selenium ide"); driver.findElement(By.id("gbqfb")).click(); Thread.sleep(1000); driver.findElement(By .xpath("//ol[@id='rso']/div/li[2]/div/h3/a/em")).click(); assertEquals("Selenium IDE is a Firefox plugin … for any kind of resiliency.", driver.findElement(By .xpath("//div[@id='mainContent']/p[2]")).getText()); } }
  • 6. Explicit/Implicit Waits ▪ Implicit Waits – An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. – The default setting is 0. – Once set, the implicit wait is set for the life of the WebDriver object instance.
  • 7. Explicit/Implicit Waits import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.WebDriverWait; public class Selenium2Example { public static void main(String[] args) { // Create a new instance of the Firefox driver WebDriver driver = new FirefoxDriver(); // And now use this to visit Google driver.get("http://www.google.com");
  • 8. Explicit/Implicit Waits // Alternatively the same thing can be done like this // driver.navigate().to("http://www.google.com"); // Find the text input element by its name WebElement element = driver.findElement(By.name("q")); // Enter something to search for element.sendKeys("Cheese!"); element.submit(); // Check the title of the page System.out.println("Page title is: " + driver.getTitle());
  • 9. Explicit/Implicit Waits // Google's search is rendered dynamically with JavaScript. // Wait for the page to load, timeout after 10 seconds (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } } ); // Should see: "cheese! - Google Search" System.out.println("Page title is: " + driver.getTitle()); // Close the browser driver.quit(); } }
  • 10. WebDriverWait ▪ Anonymous classes enable you to make your code more concise. ▪ They enable you to declare and instantiate a class at the same time. ▪ They are like local classes except that they do not have a name. ▪ Use them if you need to use a local class only once. (new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver d) { return d.getTitle().toLowerCase().startsWith("cheese!"); } } );
  • 11. WebDriverWait ▪ This is equivalent to: class MyExpectedCondition extends ExpectedCondition<Boolean> { public Boolean apply(WebDriver d) { return d.getTitle( ).toLowerCase( ).startsWith("cheese!"); } } MyExpectedCondition my = new MyExpectedCondition(); WebDriverWait wait = new WebDriverWait(driver, 10); wait.until(my);
  • 12. Explicit Waits ▪ There are some convenience methods provided that help you write code that will wait only as long as required. ▪ WebDriverWait in combination with ExpectedCondition is one way this can be accomplished. WebDriver driver = new FirefoxDriver(); driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated( By.id("myDynamicElement")));
  • 13. Explicit Waits WebElement myDynamicElement = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated( By.id("myDynamicElement"))); ▪ This waits up to 10 seconds before throwing a TimeoutException or if it finds the element will return it in 0 – 10 seconds. ▪ WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully. ▪ A successful return is for ExpectedCondition type is Boolean return true or not null return value for all other ExpectedCondition types.
  • 14. Explicit Waits ▪ Java to have convienence methods so you don’t have to code an ExpectedCondition class yourself or create your own utility package for them. ▪ Element is Clickable – it is Displayed and Enabled WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable( By.id("someid")));
  • 15. Implicit Waits ▪ An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
  • 16. WebDriver Wait Commands ▪ Listing out the different WebDriver Wait statements that can be useful for an effective scripting and can avoid using the Thread.sleep() comamnds.
  • 18. WebDriver Wait ▪ implicitlyWait ▪ The ImplicitWait will tell the webDriver to poll the DOM for a certain duration when trying to find the element, this will be useful when certain elements on the webpage will not be available immediately and needs some time to load. ▪ By default it ill take the value to 0, for the life of the WebDriver object instance through out the test script. WebDriver driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("http://somedomain/url_that_delays_loading"); WebElement myDynamicElement = driver.findElement(By.id("myDynamicElement"));
  • 19. WebDriver Wait. Timeout ▪ pageLoadTimeout – Sets the amount of time to wait for a page load to complete before throwing an error. – If the timeout is negative, page loads can be indefinite. driver.manage().timeouts().pageLoadTimeout(100, SECONDS); ▪ setScriptTimeout – Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. – If the timeout is negative, then the script will be allowed to run indefinitely. driver.manage().timeouts().setScriptTimeout(100,SECONDS);
  • 20. WebDriver Wait ▪ FluentWait ▪ Each FluentWait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. ▪ Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
  • 21. WebDriver Wait // Waiting 30 seconds for an element to be present on the // page, checking for its presence once every 5 seconds. Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(30, SECONDS) .pollingEvery(5, SECONDS) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(By.id("foo")); } } );
  • 22. WebDriver Wait Commands ▪ ExpectedConditions ▪ Would include determining if a web page has loaded or that an element is visible. WebDriverWait wait = new WebDriverWait(driver, 10); WebElement element = wait.until(ExpectedConditions.elementToBeClickable( By.id("someid"))); ▪ WebDriverWait will be used as we used in the Expected conditions code snippet as above. ▪ Sleeper is something same as the Thread.sleep() method.
  • 23. Waits Solution long implicitlyWaitTimeout = 10; public long getImplicitlyWaitTimeout() { return implicitlyWaitTimeout; } public WebDriver getWebDriver() { driver = new FirefoxDriver(); driver.manage().timeouts() .implicitlyWait(getImplicitlyWaitTimeout(), TimeUnit.SECONDS); driver.manage().window().maximize(); return driver; }
  • 24. Waits Solution public WebElement getWebElement(String name) { WebElement webElement = new WebDriverWait( getWebDriver(), getImplicitlyWaitTimeout()) .until(ExpectedConditions .visibilityOfElementLocated(By.name(name)); if (webElement == null) { throw new RuntimeException("My Error"); } return webElement; }
  • 26. Taking a Screenshot ▪ Most of the time we think to Capture Screenshot in WebDriver when some kind of error or exception surfaces while practicing testing, to resolve the same WebDriver has provided us one interface TakesScreenshot for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver. ▪ This getScreenshotAs() method takes argument of type OutputType.File or OutputType.BASE64 or Output.BYTES.
  • 27. Taking a Screenshot ▪ We have taken the screenshot with the help of getScreenshotsAs() method and and now its time to copy this file somewhere in our file system. ▪ So for this purpose we further use copyFile() method of the FileUtils class from the org.apache.commons.io.FileUtils class. WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com.ua/"); File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // For example copy somewhere FileUtils.copyFile(scrFile, new File("c:tmpscreenshot.png"));
  • 28. Taking a Screenshot ▪ Take the screenshot in the @After test tear down method, which is run after every test. ▪ This way you will always get a screenshot for both passed and failed tests. public class TestSample { WebDriver driver; @Before public void setUp() { // Start new webdriver session, for eg using firefox driver = new FirefoxDriver(); }
  • 29. Taking a Screenshot @Test public void aTest() { driver.get("http://www.google.com.ua/"); // more test logic - test might pass or fail at this point } @After public void tearDown() { // take the screenshot at the end of every test File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // now save the screenshto to a file some place FileUtils.copyFile(scrFile, new File("c:tmpscreenshot.png")); driver.quit(); } }
  • 30. Taking a Screenshot try { File scrnsht = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); FileUtils.copyFile(scrnsht, new File("e:google_page.png")); } catch (Exception e) { e.printStackTrace(); }
  • 32. Testing Ajax Applications ▪ Many web applications contain AJAX calls. – AJAX calls don’t refresh the whole page, only a certain part of a page is refreshed. – When an AJAX call is made, while the page is waiting for a response from the server, a waiting icon appears on the page to inform the user, the page is waiting for information, this could be either a rotating circle, or a loading horizontal bar, etc. ▪ WebDriver is clever enough to wait for the whole page to load before doing any action and without the user having to specify a wait for page to load. – However, in case of AJAX calls, because the whole page is not refreshed, WebDriver has no way of knowing something is happening.
  • 33. Testing Ajax Applications ▪ http://www.w3schools.com/ajax/default.asp
  • 35. Testing Ajax Applications ▪ In AJAX driven web applications, data is retrieved from server without refreshing the page. – Using and Wait commands will not work as the page is not actually refreshed. – Pausing the test execution for a certain period of time is also not a good approach as web element might appear later or earlier than the stipulated period depending on the system’s responsiveness, load or other uncontrolled factors of the moment, leading to test failures. ▪ The best approach would be to wait for the needed element in a dynamic period and then continue the execution as soon as the element is found.
  • 36. Testing Ajax Applications ▪ This is done using waitFor commands, as waitForElementPresent or waitForVisible, which wait dynamically, checking for the desired condition every second and continuing to the next command in the script as soon as the condition is met. ▪ The best practice is to set implicitlyWait() at the beginning of each test, and use WebDriverWait() for waiting an element, or AJAX element to load.
  • 37. Testing Ajax Applications ▪ However, implicitlyWait() and WebDriverWait() do not work well together in the same test. ▪ You would have to nullify implicitlyWait() before calling WebDriverWait because implicitlyWait() also sets the "driver.findElement()" wait time. ▪ For Example, develop WaitTool. It solves the complexity of ImplicitWait and WebDriverWait, and provides easy methods to use.
  • 38. Testing Ajax Applications ▪ WaitTool handles the following tasks at the behind scene. – nullifying implicitlyWait(); – executing WebDriverWait(), and return element; – reset implicitlyWait() again.
  • 39. Testing Ajax Applications public static void waitForElementPresent(WebDriver driver, final By by, int timeOutInSecond) { try { // nullify implicitlyWait() driver.manage().timeouts() .implicitlyWait(0, TimeUnit.SECONDS); // Create web element WebElement webElement = new WebDriverWait(driver, timeOutInSecond)
  • 40. Testing Ajax Applications WebElement webElement = new WebDriverWait(driver, timeOutInSecond) .until(new ExpectedConditions<Boolean>() { @Overridew public Boolean apply(WebDriver d) { return isElementPresent(d, by); } } ); // reset implicitlyWait() driver.manage().timeouts() .implicitlyWait(10, TimeUnit.SECONDS); } catch(Exceptions e) { …
  • 41. References ▪ Explicit and Implicit Waits http://docs.seleniumhq.org/docs/04_webdriver_advanced.jsp ▪ Selenium WebDriver http://docs.seleniumhq.org/docs/03_webdriver.jsp ▪ How to Handle Ajax call in Selenium Webdriver http://agilesoftwaretesting.com/selenium-wait-for-ajax-the-right-