SlideShare a Scribd company logo
1 of 70
Follow step by step tutorial – How to learn Selenium Web Driver -
TestNG Framework ----Rashed
Step 1: Installation Process – Selenium Web Driver using eclipse
• Install Java (JDK)
• Run eclipse.exe after extract zip file
> Create a workspace folder where we will contain all the program files we create.
• Extract Web Driver Java Client downloaded zip folder.
• Configure Eclipse IDE with Web Driver:
> Create new Java Project from File > New > Project
> Right click on Project ‘XYZ‘and select New > Package name
> Right click on Package ‘ABC‘and select New >Class.
> Input your Class name e.g. ‘Login‘, check the option ‘public staticvoid main‘ and
click on Finish button
• Add External Jars to Java build path
> Right click on Project ‘XYZ‘> Select Properties > Java build path. Then navigate
to Libraries tab and click Add External JARs.
> Add Selenium Java jar
> Add all jars from the libs folder then Click OK.
• Install firebug, firepath
Now, start fromhere:
Install JDK basedon OS from below link indicating windows x86 for 32 bit OS,
x64 for 64 bit:
Following path: http://www.guru99.com/installing-selenium-webdriver.html
Install Eclipse IDE based on OS:
 Just extract zip file and click on Eclipse. Exe file.
Download the SeleniumJava Client Driver as we will use JAVA:
Configure Eclipse IDEwithWeb Driver:
 Launch the "eclipse.exe"
 Create a “working directory”
 Get a Welcome Window:
Now create a new Project, package, class (sequentially):
 Give the project Name as shown in below given figures or as per your project name
then click on Finish button
b) Give Class
name ‘e.g.
FirstTestCase‘,
check the option
‘public static
void main‘ and
click
on Finish button.
 Open ‘ selenium-java-2.45.0’ file
 Open libs folder then,
Finally you will get this following window to writescript:
After that:
 Install firebug:
1) Go to Tools > Web Developer > Get More Tools.
2) As we need Firebug, just click on Add to Firefox button for Firebug.
 Install Fire path: It is an extension to FireBug that adds a development tool to edit,
inspect and generate XPath expressions and CSS3 Selectors.
1) Go to Tools > Web Developer > Get More Tools.
2) Click on the Extensions link and the type Firepath on theSearch field. As we need
FirePath, just click on Add to Firefox button for FirePath.
Web Driver provides these useful get commands:
Get Command
Purpose: This command is use to open a new web page in the current browser.
Command: driver.get(URL);
Parameters: url – The URL to load. It is best to use a fully qualified URL
driver.get("wwww.google.com");
Get Title Command
Purpose: This command is use to get the title of the current page.
driver.getTitle();
Get Current URL Command
Purpose: This command is use to get the URL of the page currently loaded in the browser.
driver.getCurrentUrl()
Get Current URL Command
Purpose: This command is use to get the URL of the page currently loaded in the browser.
driver.getCurrentUrl()
Get Page Source Command
Purpose: This command is use to get the source of the last loaded page.
driver.getPageSource();
Close Command
Purpose: This command is use to close the current window of the browser, if it’s the last
window it will close the browser.
Web Driver provides these useful navigationcommands:
Belowsummarizing commands to access eachtype of element:
Note: Please follow next tutorial: step -2 ---- How to run test case in selenium web driver
SeleniumWebDriver tutorial is preparedby Rashedul Islam(Rashed)
BRAC It Services Ltd
Step – 2: Face book login and Gmail Registration in Selenium Web Driver using
eclipse after environment readiness from step-1:
(Just for learning) ---- Please follow my step by step tutorial.
Face book login in Selenium Web Driver(Eclipse):
//You can put package name as your choice
package automationframework;
import org.openqa.selenium.*;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FBLogin {
public static String driver;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//To get Firefox browser
WebDriver driver = new FirefoxDriver();
//To get face book page
driver.get("https://facebook.com/");
//To maximize windows
driver.manage().window().maximize();
//Input UserName
driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("user name");
//Input password
driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("password");
//Select Checkbox
driver.findElement(By.xpath(".//*[@id='persist_box']")).click();
//click on Login button to login into FB
driver.findElement(By.xpath(".//*[@id='u_0_n']")).click();
//To Show successful login message
System.out.println(" Successful login in Face book.");
}
}
How to Register In Gmail in Selenium Web Driver:
package automationframework;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class RegistrationInGmail {
public String driver;
public static void main(String[] args) {
// TODO Auto-generated method stub
WebDriver driver =new FirefoxDriver();
driver.get("https://www.gmail.com/intl/en/mail/help/about.html");
//To Maximize Windows
driver.manage().window().maximize();
//click on Create new account link
//I have used other locator like id, name locator also for your better
Understanding and how to use another locator.
//driver.findElement(By.id("gmail-create-account")).click();
driver.findElement(By.xpath(".//*[@id='gmail-create-account']")).click();
//Input first name
//sendkeys() is used to input data in field
driver.findElement(By.xpath(".//*[@id='FirstName']")).sendKeys("Rashed");
//Input Last Name
driver.findElement(By.xpath(".//*[@id='LastName']")).sendKeys("Mahmud");
//Input User name
driver.findElement(By.xpath(".//*[@id='GmailAddress']")).sendKeys("Give username");
//Input password
driver.findElement(By.xpath(".//*[@id='Passwd']")).sendKeys("Give password");
//Confirm Password
driver.findElement(By.xpath(".//*[@id='PasswdAgain']")).sendKeys("Give password");
//BirrthDay Month Day year Select
driver.findElement(By.xpath(".//*[@id='BirthMonth']/div")).click();
driver.findElement(By.xpath(".//*[@id=':5']/div")).click();
driver.findElement(By.id("BirthDay")).sendKeys("16");
driver.findElement(By.id("BirthYear")).sendKeys("1978");
//Select gender
driver.findElement(By.xpath(".//*[@id='Gender']/div")).click();
driver.findElement(By.xpath(".//*[@id=':f']/div")).click();
//Input Phone Number
//driver.findElement(By.name("RecoveryPhoneNumber")).sendKeys("Mobile no");
driver.findElement(By.xpath(".//*[@id='RecoveryPhoneNumber']")).sendKeys("Mobile
number for Bangladesh country code");
//Skip Captcha
driver.findElement(By.xpath(".//*[@id='SkipCaptcha']")).click();
//Select Terms & Condition Check box
//driver.findElement(By.id("TermsOfService")).click();
driver.findElement(By.xpath(".//*[@id='TermsOfService']")).click();
//Click on Next Step link
//driver.findElement(By.id("submitbutton")).click();
driver.findElement(By.xpath(".//*[@id='submitbutton']")).click();
//Verify Phone number in Verify your account page
//driver.findElement(By.id("next-button")).click();
//click on Continue button
driver.findElement(By.xpath(".//*[@id='next-button']")).click();
//Input verification code no
//driver.findElement(By.id("verify-phone-input")).sendKeys("908545");
driver.findElement(By.xpath(".//*[@id='verify-phone-input']")).sendKeys("verification
code no: e.g 435057");
//Click on Continue button
driver.findElement(By.xpath(".//*[@id='signupidv']/div[1]/div[2]/input[2]")).click();
//driver.findElement(By.name("VerifyPhone")).click();
//Wait 20 second for next execution
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//To show sign up message
System.out.println(" Gmail sign up done Successfully .");
//To close browser
driver.quit();
//To close specific browser window
//driver.close();
}
}
Notedthat I have usedother locator like id, name locator’s alsofor your better
understanding andhow touse another locator.
What is Xpath and how to find out Xpath that is given in below
information:
What is X path?
X-Path is used in Selenium to uniquely identify an element on a Webpage as element locator
just like the way we use Post Code and House address in real world to locate Home Address.
There is a good chance that your x-path will vary in every release. It is always better to
choose Relative x path, as it helps us to reduce the chance of element not found exception.
To choose the relative x path, it is advisable to look for the recent Id attribute.
Absolute xpath: /html/body/div[2]/div/div/footer/section[3]/div/ul/li[3]/a
Relative x path: //*[@id=’social-media’]/ul/li[3]/a ……….. (Better choice to use)
Absolute x path is using single slash at the start of the x path and relative is using double slash.
 To get X-path:
 Notedthat youcan use CSS Selectorlocator
Please follow next tutorial: Step -3 ----Environment readiness on TestNG framework in
Selenium Web Driver
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step 3: Environment readiness on TestNG Framework – Selenium Web
Driver
What is TestNG?
 TestNG is a testing framework that is capable of making Selenium tests easier to
understand and of generating reports that are easy to understand.
 TestNG is a testing framework inspired from JUnit and NUnit.
 TestNG is an open source automated testing framework; where NG of
TestNG means Next Generation. TestNG is similar to JUnit but it is much more powerful
than JUnit
 TestNG eliminates most of the limitations of the Junit framework and gives the
developer the ability to write more flexible and powerful tests with help of easy
annotations, grouping, sequencing & parameterizing.
Advantages of TestNG over JUnit:
 Annotations are easier to understand
 No method dependency, you can use different methods as per priority basis.
 TestNG is capable of generating HTML-based reports.
 Test cases can be grouped & Prioritized more easily
 Parallel testing is possible
 Generates Logs
 Data Parameteriz ation is possible
Why we use Annotations:
Annotations in TestNG are lines of code that can control how the method below them will be
executed. They are always preceded by the @ symbol.
Installation of TestNG inTestNG framework:
1) Launch the Eclipse IDE and from Help menu, click “Install New Software”.
2) You will see a dialog window, click “Add” button.
3) Type name as you wish, let’s take “TestNG” and type “http://beust.com/eclipse/” as
location. Click OK.
4. Just Click on TestNG and press “Next” button.
5) Click “I accept the terms of the license agreement” then click Finish.
6) You may or may not encounter a Security warning, if in case you do just click OK.
7) Click next again on the succeeding dialog box until it prompts you to restart the Eclipse.
8) You are all done now, just click Yes.
9) Proceed with your workplace.
Now it is the time to write the first TestNG test case.
Please follow next tutorial: Step - 4 ---Test Case execution and generated HTML report
On
TestNG framework in Selenium Web Driver
Step by step, I will share with you all different practice solution.
Please let me know feel free if you need to understand or share any suggestion or
problem regarding these step by Step tutorial’s and stay with us
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step 4: How to execute test case on TestNG Framework – Selenium
Web Driver
How to loginand Logout in Gmail in - TestNG Framework
package automationframework; // package name, you may choice the name
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class GmailLoginTestNG {
public WebDriver driver;
// @Test: Main functionality is performed here
@Test
//public void f() { : you can use any method name here like I have been used
GmailLoginLogout.
//There is no dependency about main method.
//Please use valid user name/password
public void GmailLoginLogout() {
//Click on Sign In
driver.findElement(By.xpath(".//*[@id='gmail-sign-in']")).click();
//Enter User name
driver.findElement(By.id("Email")).sendKeys("user name or Email address");
//Click on Next button
driver.findElement(By.xpath(".//*[@id='next']")).click();
//Enter password
driver.findElement(By.id("Passwd")).sendKeys("password*");
//Wait some time for next
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//Click on Sign In button
driver.findElement(By.xpath(".//*[@id='signIn']")).click();
//To show output message
System.out.println("login in Gmail Successfully.");
//click on icon from right top of page
driver.findElement(By.xpath(".//*[@id='gb']/div[1]/div[1]/div[2]/div[4]/div[1]
/a/span")).click();
//Click on Logout
driver.findElement(By.xpath(".//*[@id='gb_71']")).click();
//To show output message
System.out.println("Logout Successfully.");
}
//@BeforeMethod: To Launch specific browser by application URL
@BeforeMethod
public void beforeMethod() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//To launch into application
driver.get("https://www.gmail.com/intl/en/mail/help/about.html");
//To maximize browser
driver.manage().window().maximize();
}
//@AfterMethod is used to close browser
@AfterMethod
public void afterMethod() {
//driver.quit(); //you can use for close browser.
}
}
Mail Sent in Gmail in Selenium Web Driver – TestNG Framework
package automationframework;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class MailSendInGmailTestNG {
public WebDriver driver;
// @Test: Main functionality is performed here
@Test
//public void f() { : you can use any method name here like MailSendInGmail.
//There is no dependency about main method.
//
public void f() {
//Click on Sign In
driver.findElement(By.xpath(".//*[@id='gmail-sign-in']")).click();
//Enter User name
driver.findElement(By.id("Email")).sendKeys("user name or E-mail address");
//Click on Next button
driver.findElement(By.xpath(".//*[@id='next']")).click();
//Enter password
driver.findElement(By.id("Passwd")).sendKeys("password*");
//Wait some time for next
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
//Click on Sign In button
driver.findElement(By.xpath(".//*[@id='signIn']")).click();
//To show output message
System.out.println("login in Gmail Successfully.");
//For Compose Mail
driver.findElement(By.xpath(".//*[@id=':3m']/div/div")).click();
//To Mail
driver.findElement(By.className("vO")).sendKeys("E-mail address");
//Subject
driver.findElement(By.className("aoT")).sendKeys("Test Mail - Rashed");
//Send Button Click
driver.findElement(By.xpath("//div[text()='Send']")).click();
//To show output message
System.out.println("Mail sent in Gmail Successfully.");
}
//@BeforeMethod: To Launch specific browser by application URL
@BeforeMethod
public void beforeMethod() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//To launch application in Browser
driver.get("https://www.gmail.com/intl/en/mail/help/about.html");
//To maximize browser
driver.manage().window().maximize();
}
//@AfterMethod is used to close browser
@AfterMethod
public void afterMethod() {
//driver.quit(); // use to close browser
}
}
Showing generated HTML report in TestNG Framework
10) TestNG also produce ‘index.html‘ report and it resides in the sametest-
output folder.
Please follow next tutorial: Step – 5: How to execute multiple test cases in a Test Suite
On
TestNG framework in Selenium Web Driver
Step by step, I will share with you all different practice solution like previous.
Please let me know feel free if you need to understand or share any suggestion or
Problem regarding these step by Step tutorial’s and stay with us
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step 5: How to execute multiple test cases under a Test Suite in
– Selenium Web Driver - TestNG Framework
Suppose, we need to execute so many test cases on a run. Running a set of test cases
together is call executing a Test Suite. TestNG framework gives us the capability to
manage such kind of test execution.
In TestNG framework, we need to create testng.xml file to create and handle multiple
test classes. This is the xml file where we will configure our test run, set test
dependency, include or exclude any test, method, class or package and set priority etc.
Please follow following steps to execute multiple test cases under a test suite:
 Right click on Project folder, go to New and select ‘File‘
 Add file name = ‘testng.xml‘ as your choice then click on Finish
 Observe that already added testng.xml file under your project folder
 Add XML code under Source code section.
 You can add one or more class to execute under a test suite using XML file
 Run script following: Right click on the testng.xml file and select Run As> TestNG Suite
Let see briefly:
1) Right click on Project folder, go to New and select ‘File‘
2) In New file wizard, add file name = ‘testng.xml‘as shown in below given image
and click on Finish button. You can use another file name like ‘abc.xml’
2) Observe that already added testng.xml file under your project folder.
Now create a XML file:
 Add following code in testing.xml under‘Source code’ to create a xml file:
<suite name="Test-Suite"> …………..anysuitename
<testname="ToolsQA"> ……………. …………..anytestname
<classes>
<classname="automationFramework.SubmitFormTestNG"/> …… WhichTestNG test case
(SubmitFormTestNG) wewill run
<classname="automationFramework.TestNG"/>…………Which TestNG test case (TestNG) we
will run
</classes>
</test>
</suite>
Note:automationFramework(packagename).SubmitFormTestNG(createdTestNG test case
or class),another class or test case name TestNG.
 You can create single xml file,here I have addedtwo classeswhere two test cases will be
executedone by one.
 If you mentionone class like <classname="automationFramework.SubmitFormTestNG"/>
Then only ‘SubmitFormTestNG’testcasewill be executed asper yourmentioned class from
above.
As for example frommy practice howto create xml file and run multiple test
cases at a time
Executing testing.xml withtest suite:
 Right click on the testng.xml file and select Run As> TestNG Suite like below:
Please follow next tutorial: Step – 6: Multi browser parallel testing
On
TestNG framework - Selenium Web Driver
Step by step, I will share with you all different practice solution like previous.
Please let me know feel free if you need to understand or share any suggestion or
Problem regarding this step by Step tutorials
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step – 6: Multi Browser parallel testing inSeleniumWebDriver –TestNG
Framework
What is Multi Browser Testing?
Multi Browser Testing/Cross Browser Testing is a type of functional test to check that
the web application works as expected in different browsers.
Why do we need Multi/Cross Browser Testing?
Web based applications are totally different from windows applications.
A web application can be opened in any browser by the end user.
For example, some people prefer to open http://facebook.com in Firefox browser, while
other’s can be using Chrome browser or IE.
At a glance, following instruction need to perform Multi/cross Browser Parallel Testing in
different browsers as per my below practice code:
 Using three (3) browser’s for parallel testing.
 Download Driver.exe for browsers.
//ChromeDriver.exe download link:
http://code.google.com/p/selenium/wiki/ChromeDriver
IE: // 32 bits http://selenium-
release.storage.googleapis.com/2.42/IEDriverServer_Win32_2.42.0.zip
// 64 bits http://selenium
release.storage.googleapis.com/2.42/IEDriverServer_x64_2.42.0.zip
 Passing the value of parameter 'browser' as 'firefox' for executing specific browsers like
Firefox browser that will be able to execute Firefox Driver so that we can run test case on
Firefox browser. Similarly for others browser like ‘chrome’for Chrome, ‘ie’ for IE.
 Specify the path by ‘setProperty’ method like
‘System.setProperty("webdriver.chrome.driver","E:chromedriver_win32chromedriv
er.exe"); where the downloaded driver.exe is available
In xml file:
 Set parallel="tests" for parallel testing, parameter: “browser”, class name:
"automationFramework.TestNGMultiBrowser" where automationFramework: package
name and TestNGMultiBrowser: Class Name or Test case name.
 parallel="none" for single browser testing.
 Then, run xml file to perform parallel testing.
Following code to execute for multi browser parallel testing:
package automationFramework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class TestNGMultiBrowser {
public WebDriver driver;
@BeforeMethod
@Parameters("browser")
public void beforeMethod(String browser) {
//Check if parameter passed from TestNG as 'firefox'
if(browser.equalsIgnoreCase("firefox")) {
//create firefox instance
driver = new FirefoxDriver();
//Check if parameter passed as 'chrome'
}
else if (browser.equalsIgnoreCase("chrome")) {
// specify the located driver.exe path by setProperty method
System.setProperty("webdriver.chrome.driver","E:chromedriver_win32chromedr
iver.exe");
//create chrome instance
driver = new ChromeDriver();
}
//Check if parameter passed as 'ie'
else if (browser.equalsIgnoreCase("ie")) {
// specify the located driver.exe path by setProperty method
System.setProperty("webdriver.ie.driver",
"E:IEDriverServer_Win32_2.39.0IEDriverServer.exe");
driver = new InternetExplorerDriver();
}
else
{
throw new IllegalArgumentException("The Browser Type is
Undefined");
}
}
@Test
public void f() {
driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html");
driver.manage().window().maximize();
driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("Rashed");
driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("mahmud");
driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("fdf@gmail.c
om);
driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("3343");
driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("Brac It Services
Ltd");
driver.findElement(By.xpath(".//*[@id='post-body-
8228718889842861683']/div[1]/form/input[6]")).
submit();
}
@AfterMethod
public void afterMethod() {
//driver.quit();
} }
XML file configuration:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite" parallel="tests"> //for parallel testing
<test name="FirefoxTest">
<parameter name="browser" value="firefox" /> //passing parameter: ‘browser’
<classes>
<class name="automationFramework.TestNGMultiBrowser" /> //which class will be
executed under package
</classes>
</test>
<test name="ChromeTest">
<parameter name="browser" value="chrome" />
<classes>
<class name="automationFramework.TestNGMultiBrowser" />
</classes>
</test>
<test name="IETest">
<parameter name="browser" value="ie" />
<classes>
<class name="automationFramework.TestNGMultiBrowser" />
</classes>
</test>
</suite>
Please follownext tutorial:Step –7: How to take a Screenshot
In
TestNG framework - Selenium Web Driver
Step by step, I will share with you all different practice solution like previous.
Please let me know feel free if you need to understand or share any suggestion or
Problem regarding this step by Step tutorials
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step – 7: Taking a screenshot inSeleniumWebDriver –TestNG
Framework
At a glance, for better understanding before code practice
I have used TakesScreenshot (one kind of Interface) for capturing the screenshot of web
application and This interface provides one method names as getScreenshotAs() to capture
screenshot in instance of driver.
Here, This getScreenshotAs() method takes argument of type OutputType.File so that it
returns captured screenshot in File type.
Like, For File type:
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
getScreenshotsAs() method is used to take a screenshot.
Now its time to copy and save this file somewhere in your file system or in your PC. For this
purpose I have used copyFile() method of the FileUtils class from
the org.apache.commons.io.FileUtils class.
FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot3.png"), true);
Here, “D:seleniumscreenshot3.png” screenshot saving path and screenshot will save as
name screenshot3 in png format.
Noted that you can use any format oryour choice path.
Here, copyFile is a method of Class FileUtils and to call this method we need to write
class.method() and in above code copyFile is taking argument from getScreenShotsAs() and new
location where we want to save this captured Screenshot with name and with extension.
Following code to execute for taking screenshot inTestNG Framework:
package automationFramework;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.AfterMethod;
public class ScreenshotTestNG {
WebDriver driver = new FirefoxDriver();
@Test
public void TakingScreenShot() throws IOException {
// Take screenshot and store it as a file format
try {
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Copy and save the screenshot name (screenshot1.png) in below desired path using
copyFile method
FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot3.png"), true);
System.out.println("Taken screenshot successfully");
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
}
@BeforeMethod
public void beforeMethod() {
// Wait For Page To Load
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Get application
driver.get("http://www.facebook.com/");
// Maximize Window
driver.manage().window().maximize();
}
@AfterMethod
public void afterMethod() {
driver.quit();
}
}
Using only Eclipse (not for TestNG framework):
package automationFramework;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Screen_shot {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
WebDriver driver = new FirefoxDriver();
// Wait For Page To Load
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Go to URL
driver.get("http://www.facebook.com/");
// Maximize Window
driver.manage().window().maximize();
// Take screenshot and store it as a file format
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Copy and save the screenshot name (screenshot1.png) in below desired
path using copyFile method
FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot1.png"),
true);
// Close Driver
driver.quit();
}
}
Please follow next tutorial: Step – 8: How to handle Pop Up Alert, Conformation Alert
And Prompt alert
On
TestNG framework - Selenium Web Driver
Step by step, I will share with you all different practice solution like previous.
Please let me know feel free if you need to understand or share any suggestion or
Problem regarding this step by Step tutorials
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!
Step – 8: How to handle simple alert popup, ConformationPop Up and
Prompt Pop Up in SeleniumWebDriver –TestNG Framework
At a glance, for better understanding before code practice
Alertisa pop upwindowthatcomesup on screen.
T here has some alertpopup such as:
 Simple Alertpopup
 ConformationAlert PopUp
 PromptAlertPopUp
Confirmationpopupisalsoa type of alertpopup. The differencebetweenalertpopup , confirmation
popup and promptpop up is that alertpopup containssingle button ,confirmationpopupcontains
twobuttons“OK” and “CANCEL”whereas promptpopup containsingle inputvalue field, twobuttons
“OK” and “CANCEL”.
Simple Alertpop up
ConformationAlert Pop Up
Prompt Alert Pop Up
At a glance
 Save HTML code as (.html) format in your PC thenspecifythis URL to getapplication pop up
by driver.get(“…..”) incode.
 driver.switchTo().alert(); -- to get alertpop up
 I have usedaccept () methodto clickon OK button and dismiss() method for CANCEL.
 sendKeys("Rashed"); -- To sendinput value
Let’s practice fromhere stepby step for three (3) all:
Simple Alert Pop Up:
An alertbox isusedif anyone wantsto make sure informationcomesthroughtothe user.
Firstly,Save below HTMLcode as (.html) formatwhichwill displays simplealertpopup withok button.
Afterthat,we will automate it.
Copy belowhtml code and save as an html file inyour PC:
<html>
<head>
<title>Hi Rashed!Alertpopup </title>
</head>
<body>
<h2> Rashed! AlertPopUp </h2>
<fieldset>
<legend>AlertBox</legend><p>Clickthe buttontodisplayanalertbox.</p>
<buttononclick="alertFunction()">Clickonme</button>
<script>
functionalertFunction()
{
alert("Iaman example foralertbox!");
}
</script>
</fieldset>
</body>
</html>
 Notedthatif youclickon alert.html thensimple alertpopupwill show (foryourbetter
understanding).
Following code to execute for Simple AlertPop upin TestNG Framework:
package PopUpTestNG;
// Import this package to handle the web based alerts in Web Driver.
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class alertTestNG {
WebDriver driver=new FirefoxDriver();
@Test
public void PopUpAlert() throws InterruptedException {
//To maximize the window
driver.manage().window().maximize();
//Specified Path to get the application where I have saved the HTML code, you use
saved path from your PC
driver.get("file:///D:/Selenium Web Driver Practice/popuppractice/alert.html");
Thread.sleep(2000);
//Click on ‘Click on me’ button
driver.findElement(By.xpath("html/body/fieldset/button")).click();
Thread.sleep(2000);
//To get alert pop up window
Alert PopUpAlert = driver.switchTo().alert();
//To get alert Pop up text
String alertText = PopUpAlert.getText();
//To show text as output
System.out.println("Alert text is " + alertText);
//To click on OK button and accept alert pop up
PopUpAlert.accept();
}
}
Conformation Alert pop up:
A confirmbox isusedif anyone wantthe userto verifyoraccept something.
Secondly,Save belowHTML code as (.html) format whichwill displays confirmation popupwithok and
Cancel button.
Afterthat,we will automate it.
Copy belowcode and save as an html file inyour PC:
<html>
<head>
<title>Hi Rashed! ConfirmpopupSample </title>
</head>
<body>
<h2> Rashed! Confirmpopup</h2>
<fieldset>
<legend>RashedConfirmBox</legend>
<p>Clickthe buttonto displaya confirmbox.</p>
<buttononclick="confirmFunction()">Clickonme</button>
<p id="confirmdemo"></p>
<script>
functionconfirmFunction()
{
var cb;
var c=confirm("Iaman Example forConfirmBox.nPress anybutton!");
if (c==true)
{
cb="You ClickedonOK!";
}
else
{
cb="You ClickedonCancel!";
}
document.getElementById("confirmdemo").innerHTML=cb;
}
</script>
</fieldset>
</body>
Following code to execute for Conformation Popup in TestNG Framework:
package PopUpTestNG;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class ConfirmPopUpTestNG {
WebDriver driver=new FirefoxDriver();
@Test
public void ConfirmPopUp() throws InterruptedException {
driver.manage().window().maximize();
//Specified Path to get the application where I have saved the HTML code
driver.get("file:///D:/Selenium Web Driver
Practice/popuppractice/ConfirmPopUp.html");
Thread.sleep(2000);
driver.findElement(By.xpath("html/body/fieldset/button")).click();
Thread.sleep(2000);
//To switch or get conformation pop up
Alert confirmationAlert = driver.switchTo().alert();
String alertText = confirmationAlert.getText();
System.out.println("Alert text is " + alertText);
// use anyone(OK or Cancel) as per your need
//To accept alert or click on Ok button
confirmationAlert.accept();
//To cancel alert or click on Cancel button
confirmationAlert.dismiss();
}
}
Prompt Alert:
A promptbox is usedif anyone wantsthe userto inputa value before enteringapage.
Thirdly,Save below HTMLcode as (.html) format whichwilldisplayspromptpopup withaninputvalue
field,ok andCancel button.
Afterthat,we will automate it.
Copy belowcode and save as an html file inyour PC:
<html>
<head>
<title>Hi Rashed!Here isa PromptpopupSample </title>
</head>
<body>
<h2> Hi Rashed!PromptPopUp</h2>
<fieldset>
<legend>PromptBox</legend>
<p>Clickthe buttonto demonstrate the promptbox.</p>
<buttononclick="promptFunction()">Clickonme</button>
<p id="promptdemo"></p>
<script>
functionpromptFunction()
{
var x;
var person=prompt("Please enteryourname","Yourname");
if (person!=null)
{
x="Hello"+ person+ "! Welcome to Rashed..";
document.getElementById("promptdemo").innerHTML=x;
}
}
</script>
</fieldset> </body> </html>
Following code to execute for Prompt Pop up in TestNG Framework:
package PopUpTestNG;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class PromptPopUp {
WebDriver driver=new FirefoxDriver();
@Test
public void PromptPopUp() throws InterruptedException {
driver.manage().window().maximize();
//Specified Path to get the application where I have saved the HTML code
driver.get("file:///D:/Selenium Web Driver
Practice/popuppractice/PromptPopUp.html");
Thread.sleep(2000);
driver.findElement(By.xpath("html/body/fieldset/button")).click();
Thread.sleep(2000);
Alert PromptnAlert = driver.switchTo().alert();
// Get Prompt pop up and send value by sendkeys()
driver.switchTo().alert().sendKeys("Rashed");
//To accept prompt pop up or click on ok button
PromptnAlert.accept();
//System.out.println(PromptnAlert.getText());
//To Cancel prompt pop up or click on Cancel button
//PromptnAlert.dismiss();
}
}
Please follow next tutorial: Step – 9: How to upload/download a file
On
TestNG framework - Selenium Web Driver
Step by step, I will share with you all different practice solution like previous.
Please let me know feel free if you need to understand or share any suggestion or
Problem regarding this step by Step tutorials
SeleniumWebDriver tutorial is prepared &presented by
Rashedul Islam(Rashed)
BRAC It Services Ltd
Best of Luck!

More Related Content

What's hot

Tellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.TestingTellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.TestingJohn.Jian.Fang
 
Step by step - Selenium 3 web-driver - From Scratch
Step by step - Selenium 3 web-driver - From Scratch  Step by step - Selenium 3 web-driver - From Scratch
Step by step - Selenium 3 web-driver - From Scratch Haitham Refaat
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Oren Rubin
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed introRich Helton
 
Protractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine ReportersProtractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine ReportersHaitham Refaat
 
selenium training | selenium course | selenium video tutorial | selenium for ...
selenium training | selenium course | selenium video tutorial | selenium for ...selenium training | selenium course | selenium video tutorial | selenium for ...
selenium training | selenium course | selenium video tutorial | selenium for ...Nancy Thomas
 
Accelerate your Lotus Domino Web Applications with Dojo and XPages
Accelerate your Lotus Domino Web Applications with Dojo and XPagesAccelerate your Lotus Domino Web Applications with Dojo and XPages
Accelerate your Lotus Domino Web Applications with Dojo and XPagesDavalen LLC
 
Behat - Drupal South 2018
Behat  - Drupal South 2018Behat  - Drupal South 2018
Behat - Drupal South 2018Berend de Boer
 
Make XCUITest Great Again
Make XCUITest Great AgainMake XCUITest Great Again
Make XCUITest Great AgainKenneth Poon
 
Implementing xpages extension library
Implementing xpages extension libraryImplementing xpages extension library
Implementing xpages extension librarydominion
 
Creating Your First WordPress Plugin
Creating Your First WordPress PluginCreating Your First WordPress Plugin
Creating Your First WordPress PluginBrad Williams
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.SWAAM Tech
 

What's hot (19)

Selenium web driver
Selenium web driverSelenium web driver
Selenium web driver
 
Tellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.TestingTellurium.A.New.Approach.For.Web.Testing
Tellurium.A.New.Approach.For.Web.Testing
 
Step by step - Selenium 3 web-driver - From Scratch
Step by step - Selenium 3 web-driver - From Scratch  Step by step - Selenium 3 web-driver - From Scratch
Step by step - Selenium 3 web-driver - From Scratch
 
Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014Page Objects Done Right - selenium conference 2014
Page Objects Done Right - selenium conference 2014
 
Tumbleweed intro
Tumbleweed introTumbleweed intro
Tumbleweed intro
 
Protractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine ReportersProtractor Testing Automation Tool Framework / Jasmine Reporters
Protractor Testing Automation Tool Framework / Jasmine Reporters
 
selenium training | selenium course | selenium video tutorial | selenium for ...
selenium training | selenium course | selenium video tutorial | selenium for ...selenium training | selenium course | selenium video tutorial | selenium for ...
selenium training | selenium course | selenium video tutorial | selenium for ...
 
Accelerate your Lotus Domino Web Applications with Dojo and XPages
Accelerate your Lotus Domino Web Applications with Dojo and XPagesAccelerate your Lotus Domino Web Applications with Dojo and XPages
Accelerate your Lotus Domino Web Applications with Dojo and XPages
 
Introduction to Selenium Web Driver
Introduction to Selenium Web DriverIntroduction to Selenium Web Driver
Introduction to Selenium Web Driver
 
Behat - Drupal South 2018
Behat  - Drupal South 2018Behat  - Drupal South 2018
Behat - Drupal South 2018
 
Selenium
SeleniumSelenium
Selenium
 
Make XCUITest Great Again
Make XCUITest Great AgainMake XCUITest Great Again
Make XCUITest Great Again
 
Selenium WebDriver FAQ's
Selenium WebDriver FAQ'sSelenium WebDriver FAQ's
Selenium WebDriver FAQ's
 
Meteor Day Talk
Meteor Day TalkMeteor Day Talk
Meteor Day Talk
 
ADF in action 1.2
ADF in action 1.2ADF in action 1.2
ADF in action 1.2
 
Automation Testing by Selenium Web Driver
Automation Testing by Selenium Web DriverAutomation Testing by Selenium Web Driver
Automation Testing by Selenium Web Driver
 
Implementing xpages extension library
Implementing xpages extension libraryImplementing xpages extension library
Implementing xpages extension library
 
Creating Your First WordPress Plugin
Creating Your First WordPress PluginCreating Your First WordPress Plugin
Creating Your First WordPress Plugin
 
Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.Laravel - Website Development in Php Framework.
Laravel - Website Development in Php Framework.
 

Similar to Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-TestNG framework

Selenium for Tester.pdf
Selenium for Tester.pdfSelenium for Tester.pdf
Selenium for Tester.pdfRTechRInfoIT
 
Selenium webcrawler
Selenium webcrawlerSelenium webcrawler
Selenium webcrawlerRabia Khalid
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriverRajathi-QA
 
Selenium Training in Chennai Demo Part-2
Selenium Training in Chennai Demo Part-2 Selenium Training in Chennai Demo Part-2
Selenium Training in Chennai Demo Part-2 Thecreating Experts
 
Selenium with testng and eclipse ide
Selenium with testng and eclipse ideSelenium with testng and eclipse ide
Selenium with testng and eclipse ideTestertester Jaipur
 
Selenium training
Selenium trainingSelenium training
Selenium trainingShivaraj R
 
Uploading files using selenium web driver
Uploading files using selenium web driverUploading files using selenium web driver
Uploading files using selenium web driverPankaj Biswas
 
Selenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaSelenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaEr. Sndp Srda
 
Selenium tools-installation
Selenium tools-installationSelenium tools-installation
Selenium tools-installationITeLearn
 
Selenium tools-installation
Selenium tools-installationSelenium tools-installation
Selenium tools-installationIT eLearn
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress pluginAnthony Montalbano
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Ondřej Machulda
 
Selenium Automation in Java Using HttpWatch Plug-in
 Selenium Automation in Java Using HttpWatch Plug-in  Selenium Automation in Java Using HttpWatch Plug-in
Selenium Automation in Java Using HttpWatch Plug-in Sandeep Tol
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in detailsMax Klymyshyn
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Puneet Kala
 
Steps to write Selenium
Steps to write Selenium  Steps to write Selenium
Steps to write Selenium Rohit Thakur
 

Similar to Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-TestNG framework (20)

Selenium.pptx
Selenium.pptxSelenium.pptx
Selenium.pptx
 
Selenium for Tester.pdf
Selenium for Tester.pdfSelenium for Tester.pdf
Selenium for Tester.pdf
 
Selenium webcrawler
Selenium webcrawlerSelenium webcrawler
Selenium webcrawler
 
Selenium WebDriver
Selenium WebDriverSelenium WebDriver
Selenium WebDriver
 
Selenium Training in Chennai Demo Part-2
Selenium Training in Chennai Demo Part-2 Selenium Training in Chennai Demo Part-2
Selenium Training in Chennai Demo Part-2
 
Selenium with testng and eclipse ide
Selenium with testng and eclipse ideSelenium with testng and eclipse ide
Selenium with testng and eclipse ide
 
Selenium training
Selenium trainingSelenium training
Selenium training
 
Selenium with java
Selenium with javaSelenium with java
Selenium with java
 
Automation Zaman Now
Automation Zaman NowAutomation Zaman Now
Automation Zaman Now
 
Uploading files using selenium web driver
Uploading files using selenium web driverUploading files using selenium web driver
Uploading files using selenium web driver
 
Selenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep ShardaSelenium Introduction by Sandeep Sharda
Selenium Introduction by Sandeep Sharda
 
Selenium tools-installation
Selenium tools-installationSelenium tools-installation
Selenium tools-installation
 
Selenium tools-installation
Selenium tools-installationSelenium tools-installation
Selenium tools-installation
 
Web works hol
Web works holWeb works hol
Web works hol
 
Write your first WordPress plugin
Write your first WordPress pluginWrite your first WordPress plugin
Write your first WordPress plugin
 
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
Selenium & PHPUnit made easy with Steward (Berlin, April 2017)
 
Selenium Automation in Java Using HttpWatch Plug-in
 Selenium Automation in Java Using HttpWatch Plug-in  Selenium Automation in Java Using HttpWatch Plug-in
Selenium Automation in Java Using HttpWatch Plug-in
 
LvivPy - Flask in details
LvivPy - Flask in detailsLvivPy - Flask in details
LvivPy - Flask in details
 
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
Selenium-Webdriver With PHPUnit Automation test for Joomla CMS!
 
Steps to write Selenium
Steps to write Selenium  Steps to write Selenium
Steps to write Selenium
 

Step 8_7_ 6_5_4_3_2_ 1 in one_Tutorial for Begineer on Selenium Web Driver-TestNG framework

  • 1. Follow step by step tutorial – How to learn Selenium Web Driver - TestNG Framework ----Rashed Step 1: Installation Process – Selenium Web Driver using eclipse • Install Java (JDK) • Run eclipse.exe after extract zip file > Create a workspace folder where we will contain all the program files we create. • Extract Web Driver Java Client downloaded zip folder. • Configure Eclipse IDE with Web Driver: > Create new Java Project from File > New > Project > Right click on Project ‘XYZ‘and select New > Package name > Right click on Package ‘ABC‘and select New >Class. > Input your Class name e.g. ‘Login‘, check the option ‘public staticvoid main‘ and click on Finish button • Add External Jars to Java build path > Right click on Project ‘XYZ‘> Select Properties > Java build path. Then navigate to Libraries tab and click Add External JARs. > Add Selenium Java jar > Add all jars from the libs folder then Click OK. • Install firebug, firepath
  • 2. Now, start fromhere: Install JDK basedon OS from below link indicating windows x86 for 32 bit OS, x64 for 64 bit: Following path: http://www.guru99.com/installing-selenium-webdriver.html Install Eclipse IDE based on OS:
  • 3.  Just extract zip file and click on Eclipse. Exe file. Download the SeleniumJava Client Driver as we will use JAVA: Configure Eclipse IDEwithWeb Driver:  Launch the "eclipse.exe"
  • 4.  Create a “working directory”  Get a Welcome Window:
  • 5. Now create a new Project, package, class (sequentially):
  • 6.  Give the project Name as shown in below given figures or as per your project name then click on Finish button
  • 7.
  • 8. b) Give Class name ‘e.g. FirstTestCase‘, check the option ‘public static void main‘ and click on Finish button.
  • 9.
  • 10.  Open ‘ selenium-java-2.45.0’ file  Open libs folder then,
  • 11. Finally you will get this following window to writescript:
  • 12. After that:  Install firebug: 1) Go to Tools > Web Developer > Get More Tools. 2) As we need Firebug, just click on Add to Firefox button for Firebug.  Install Fire path: It is an extension to FireBug that adds a development tool to edit, inspect and generate XPath expressions and CSS3 Selectors. 1) Go to Tools > Web Developer > Get More Tools. 2) Click on the Extensions link and the type Firepath on theSearch field. As we need FirePath, just click on Add to Firefox button for FirePath.
  • 13. Web Driver provides these useful get commands: Get Command Purpose: This command is use to open a new web page in the current browser. Command: driver.get(URL); Parameters: url – The URL to load. It is best to use a fully qualified URL driver.get("wwww.google.com"); Get Title Command Purpose: This command is use to get the title of the current page. driver.getTitle(); Get Current URL Command Purpose: This command is use to get the URL of the page currently loaded in the browser. driver.getCurrentUrl() Get Current URL Command Purpose: This command is use to get the URL of the page currently loaded in the browser. driver.getCurrentUrl() Get Page Source Command Purpose: This command is use to get the source of the last loaded page. driver.getPageSource(); Close Command Purpose: This command is use to close the current window of the browser, if it’s the last window it will close the browser.
  • 14. Web Driver provides these useful navigationcommands:
  • 15.
  • 16. Belowsummarizing commands to access eachtype of element:
  • 17. Note: Please follow next tutorial: step -2 ---- How to run test case in selenium web driver SeleniumWebDriver tutorial is preparedby Rashedul Islam(Rashed) BRAC It Services Ltd
  • 18. Step – 2: Face book login and Gmail Registration in Selenium Web Driver using eclipse after environment readiness from step-1: (Just for learning) ---- Please follow my step by step tutorial. Face book login in Selenium Web Driver(Eclipse): //You can put package name as your choice package automationframework; import org.openqa.selenium.*; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class FBLogin { public static String driver; public static void main(String[] args) throws Exception { // TODO Auto-generated method stub //To get Firefox browser WebDriver driver = new FirefoxDriver(); //To get face book page driver.get("https://facebook.com/"); //To maximize windows driver.manage().window().maximize(); //Input UserName driver.findElement(By.xpath(".//*[@id='email']")).sendKeys("user name"); //Input password driver.findElement(By.xpath(".//*[@id='pass']")).sendKeys("password"); //Select Checkbox driver.findElement(By.xpath(".//*[@id='persist_box']")).click(); //click on Login button to login into FB driver.findElement(By.xpath(".//*[@id='u_0_n']")).click(); //To Show successful login message System.out.println(" Successful login in Face book."); }
  • 19. } How to Register In Gmail in Selenium Web Driver: package automationframework; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class RegistrationInGmail { public String driver; public static void main(String[] args) { // TODO Auto-generated method stub WebDriver driver =new FirefoxDriver(); driver.get("https://www.gmail.com/intl/en/mail/help/about.html"); //To Maximize Windows driver.manage().window().maximize(); //click on Create new account link //I have used other locator like id, name locator also for your better Understanding and how to use another locator. //driver.findElement(By.id("gmail-create-account")).click(); driver.findElement(By.xpath(".//*[@id='gmail-create-account']")).click(); //Input first name //sendkeys() is used to input data in field driver.findElement(By.xpath(".//*[@id='FirstName']")).sendKeys("Rashed"); //Input Last Name driver.findElement(By.xpath(".//*[@id='LastName']")).sendKeys("Mahmud"); //Input User name driver.findElement(By.xpath(".//*[@id='GmailAddress']")).sendKeys("Give username");
  • 20. //Input password driver.findElement(By.xpath(".//*[@id='Passwd']")).sendKeys("Give password"); //Confirm Password driver.findElement(By.xpath(".//*[@id='PasswdAgain']")).sendKeys("Give password"); //BirrthDay Month Day year Select driver.findElement(By.xpath(".//*[@id='BirthMonth']/div")).click(); driver.findElement(By.xpath(".//*[@id=':5']/div")).click(); driver.findElement(By.id("BirthDay")).sendKeys("16"); driver.findElement(By.id("BirthYear")).sendKeys("1978"); //Select gender driver.findElement(By.xpath(".//*[@id='Gender']/div")).click(); driver.findElement(By.xpath(".//*[@id=':f']/div")).click(); //Input Phone Number //driver.findElement(By.name("RecoveryPhoneNumber")).sendKeys("Mobile no"); driver.findElement(By.xpath(".//*[@id='RecoveryPhoneNumber']")).sendKeys("Mobile number for Bangladesh country code"); //Skip Captcha driver.findElement(By.xpath(".//*[@id='SkipCaptcha']")).click(); //Select Terms & Condition Check box //driver.findElement(By.id("TermsOfService")).click(); driver.findElement(By.xpath(".//*[@id='TermsOfService']")).click(); //Click on Next Step link //driver.findElement(By.id("submitbutton")).click(); driver.findElement(By.xpath(".//*[@id='submitbutton']")).click(); //Verify Phone number in Verify your account page //driver.findElement(By.id("next-button")).click(); //click on Continue button driver.findElement(By.xpath(".//*[@id='next-button']")).click(); //Input verification code no //driver.findElement(By.id("verify-phone-input")).sendKeys("908545");
  • 21. driver.findElement(By.xpath(".//*[@id='verify-phone-input']")).sendKeys("verification code no: e.g 435057"); //Click on Continue button driver.findElement(By.xpath(".//*[@id='signupidv']/div[1]/div[2]/input[2]")).click(); //driver.findElement(By.name("VerifyPhone")).click(); //Wait 20 second for next execution driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //To show sign up message System.out.println(" Gmail sign up done Successfully ."); //To close browser driver.quit(); //To close specific browser window //driver.close(); } } Notedthat I have usedother locator like id, name locator’s alsofor your better understanding andhow touse another locator.
  • 22. What is Xpath and how to find out Xpath that is given in below information: What is X path? X-Path is used in Selenium to uniquely identify an element on a Webpage as element locator just like the way we use Post Code and House address in real world to locate Home Address. There is a good chance that your x-path will vary in every release. It is always better to choose Relative x path, as it helps us to reduce the chance of element not found exception. To choose the relative x path, it is advisable to look for the recent Id attribute. Absolute xpath: /html/body/div[2]/div/div/footer/section[3]/div/ul/li[3]/a Relative x path: //*[@id=’social-media’]/ul/li[3]/a ……….. (Better choice to use) Absolute x path is using single slash at the start of the x path and relative is using double slash.
  • 23.  To get X-path:  Notedthat youcan use CSS Selectorlocator Please follow next tutorial: Step -3 ----Environment readiness on TestNG framework in Selenium Web Driver SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 24. Step 3: Environment readiness on TestNG Framework – Selenium Web Driver What is TestNG?  TestNG is a testing framework that is capable of making Selenium tests easier to understand and of generating reports that are easy to understand.  TestNG is a testing framework inspired from JUnit and NUnit.  TestNG is an open source automated testing framework; where NG of TestNG means Next Generation. TestNG is similar to JUnit but it is much more powerful than JUnit  TestNG eliminates most of the limitations of the Junit framework and gives the developer the ability to write more flexible and powerful tests with help of easy annotations, grouping, sequencing & parameterizing. Advantages of TestNG over JUnit:  Annotations are easier to understand  No method dependency, you can use different methods as per priority basis.  TestNG is capable of generating HTML-based reports.  Test cases can be grouped & Prioritized more easily  Parallel testing is possible  Generates Logs  Data Parameteriz ation is possible Why we use Annotations: Annotations in TestNG are lines of code that can control how the method below them will be executed. They are always preceded by the @ symbol.
  • 25. Installation of TestNG inTestNG framework: 1) Launch the Eclipse IDE and from Help menu, click “Install New Software”. 2) You will see a dialog window, click “Add” button. 3) Type name as you wish, let’s take “TestNG” and type “http://beust.com/eclipse/” as location. Click OK. 4. Just Click on TestNG and press “Next” button. 5) Click “I accept the terms of the license agreement” then click Finish. 6) You may or may not encounter a Security warning, if in case you do just click OK. 7) Click next again on the succeeding dialog box until it prompts you to restart the Eclipse. 8) You are all done now, just click Yes. 9) Proceed with your workplace.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. Now it is the time to write the first TestNG test case.
  • 32. Please follow next tutorial: Step - 4 ---Test Case execution and generated HTML report On TestNG framework in Selenium Web Driver Step by step, I will share with you all different practice solution. Please let me know feel free if you need to understand or share any suggestion or problem regarding these step by Step tutorial’s and stay with us SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 33. Step 4: How to execute test case on TestNG Framework – Selenium Web Driver How to loginand Logout in Gmail in - TestNG Framework package automationframework; // package name, you may choice the name import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; public class GmailLoginTestNG { public WebDriver driver; // @Test: Main functionality is performed here @Test //public void f() { : you can use any method name here like I have been used GmailLoginLogout. //There is no dependency about main method. //Please use valid user name/password public void GmailLoginLogout() { //Click on Sign In driver.findElement(By.xpath(".//*[@id='gmail-sign-in']")).click(); //Enter User name driver.findElement(By.id("Email")).sendKeys("user name or Email address"); //Click on Next button driver.findElement(By.xpath(".//*[@id='next']")).click(); //Enter password driver.findElement(By.id("Passwd")).sendKeys("password*"); //Wait some time for next
  • 34. driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); //Click on Sign In button driver.findElement(By.xpath(".//*[@id='signIn']")).click(); //To show output message System.out.println("login in Gmail Successfully."); //click on icon from right top of page driver.findElement(By.xpath(".//*[@id='gb']/div[1]/div[1]/div[2]/div[4]/div[1] /a/span")).click(); //Click on Logout driver.findElement(By.xpath(".//*[@id='gb_71']")).click(); //To show output message System.out.println("Logout Successfully."); } //@BeforeMethod: To Launch specific browser by application URL @BeforeMethod public void beforeMethod() { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //To launch into application driver.get("https://www.gmail.com/intl/en/mail/help/about.html"); //To maximize browser driver.manage().window().maximize(); } //@AfterMethod is used to close browser @AfterMethod public void afterMethod() { //driver.quit(); //you can use for close browser. } }
  • 35. Mail Sent in Gmail in Selenium Web Driver – TestNG Framework package automationframework; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; public class MailSendInGmailTestNG { public WebDriver driver; // @Test: Main functionality is performed here @Test //public void f() { : you can use any method name here like MailSendInGmail. //There is no dependency about main method. // public void f() { //Click on Sign In driver.findElement(By.xpath(".//*[@id='gmail-sign-in']")).click(); //Enter User name driver.findElement(By.id("Email")).sendKeys("user name or E-mail address"); //Click on Next button driver.findElement(By.xpath(".//*[@id='next']")).click(); //Enter password driver.findElement(By.id("Passwd")).sendKeys("password*"); //Wait some time for next driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); //Click on Sign In button driver.findElement(By.xpath(".//*[@id='signIn']")).click(); //To show output message System.out.println("login in Gmail Successfully."); //For Compose Mail
  • 36. driver.findElement(By.xpath(".//*[@id=':3m']/div/div")).click(); //To Mail driver.findElement(By.className("vO")).sendKeys("E-mail address"); //Subject driver.findElement(By.className("aoT")).sendKeys("Test Mail - Rashed"); //Send Button Click driver.findElement(By.xpath("//div[text()='Send']")).click(); //To show output message System.out.println("Mail sent in Gmail Successfully."); } //@BeforeMethod: To Launch specific browser by application URL @BeforeMethod public void beforeMethod() { driver = new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //To launch application in Browser driver.get("https://www.gmail.com/intl/en/mail/help/about.html"); //To maximize browser driver.manage().window().maximize(); } //@AfterMethod is used to close browser @AfterMethod public void afterMethod() { //driver.quit(); // use to close browser } }
  • 37. Showing generated HTML report in TestNG Framework
  • 38. 10) TestNG also produce ‘index.html‘ report and it resides in the sametest- output folder.
  • 39.
  • 40. Please follow next tutorial: Step – 5: How to execute multiple test cases in a Test Suite On TestNG framework in Selenium Web Driver Step by step, I will share with you all different practice solution like previous. Please let me know feel free if you need to understand or share any suggestion or Problem regarding these step by Step tutorial’s and stay with us SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 41. Step 5: How to execute multiple test cases under a Test Suite in – Selenium Web Driver - TestNG Framework Suppose, we need to execute so many test cases on a run. Running a set of test cases together is call executing a Test Suite. TestNG framework gives us the capability to manage such kind of test execution. In TestNG framework, we need to create testng.xml file to create and handle multiple test classes. This is the xml file where we will configure our test run, set test dependency, include or exclude any test, method, class or package and set priority etc. Please follow following steps to execute multiple test cases under a test suite:  Right click on Project folder, go to New and select ‘File‘  Add file name = ‘testng.xml‘ as your choice then click on Finish  Observe that already added testng.xml file under your project folder  Add XML code under Source code section.  You can add one or more class to execute under a test suite using XML file  Run script following: Right click on the testng.xml file and select Run As> TestNG Suite Let see briefly: 1) Right click on Project folder, go to New and select ‘File‘
  • 42. 2) In New file wizard, add file name = ‘testng.xml‘as shown in below given image and click on Finish button. You can use another file name like ‘abc.xml’
  • 43. 2) Observe that already added testng.xml file under your project folder.
  • 44. Now create a XML file:  Add following code in testing.xml under‘Source code’ to create a xml file: <suite name="Test-Suite"> …………..anysuitename <testname="ToolsQA"> ……………. …………..anytestname <classes> <classname="automationFramework.SubmitFormTestNG"/> …… WhichTestNG test case (SubmitFormTestNG) wewill run <classname="automationFramework.TestNG"/>…………Which TestNG test case (TestNG) we will run </classes> </test> </suite> Note:automationFramework(packagename).SubmitFormTestNG(createdTestNG test case or class),another class or test case name TestNG.  You can create single xml file,here I have addedtwo classeswhere two test cases will be executedone by one.  If you mentionone class like <classname="automationFramework.SubmitFormTestNG"/> Then only ‘SubmitFormTestNG’testcasewill be executed asper yourmentioned class from above.
  • 45. As for example frommy practice howto create xml file and run multiple test cases at a time Executing testing.xml withtest suite:  Right click on the testng.xml file and select Run As> TestNG Suite like below:
  • 46.
  • 47. Please follow next tutorial: Step – 6: Multi browser parallel testing On TestNG framework - Selenium Web Driver Step by step, I will share with you all different practice solution like previous. Please let me know feel free if you need to understand or share any suggestion or Problem regarding this step by Step tutorials SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 48. Step – 6: Multi Browser parallel testing inSeleniumWebDriver –TestNG Framework What is Multi Browser Testing? Multi Browser Testing/Cross Browser Testing is a type of functional test to check that the web application works as expected in different browsers. Why do we need Multi/Cross Browser Testing? Web based applications are totally different from windows applications. A web application can be opened in any browser by the end user. For example, some people prefer to open http://facebook.com in Firefox browser, while other’s can be using Chrome browser or IE. At a glance, following instruction need to perform Multi/cross Browser Parallel Testing in different browsers as per my below practice code:  Using three (3) browser’s for parallel testing.  Download Driver.exe for browsers. //ChromeDriver.exe download link: http://code.google.com/p/selenium/wiki/ChromeDriver IE: // 32 bits http://selenium- release.storage.googleapis.com/2.42/IEDriverServer_Win32_2.42.0.zip // 64 bits http://selenium release.storage.googleapis.com/2.42/IEDriverServer_x64_2.42.0.zip  Passing the value of parameter 'browser' as 'firefox' for executing specific browsers like Firefox browser that will be able to execute Firefox Driver so that we can run test case on Firefox browser. Similarly for others browser like ‘chrome’for Chrome, ‘ie’ for IE.  Specify the path by ‘setProperty’ method like ‘System.setProperty("webdriver.chrome.driver","E:chromedriver_win32chromedriv er.exe"); where the downloaded driver.exe is available
  • 49. In xml file:  Set parallel="tests" for parallel testing, parameter: “browser”, class name: "automationFramework.TestNGMultiBrowser" where automationFramework: package name and TestNGMultiBrowser: Class Name or Test case name.  parallel="none" for single browser testing.  Then, run xml file to perform parallel testing. Following code to execute for multi browser parallel testing: package automationFramework; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; public class TestNGMultiBrowser { public WebDriver driver; @BeforeMethod @Parameters("browser") public void beforeMethod(String browser) { //Check if parameter passed from TestNG as 'firefox' if(browser.equalsIgnoreCase("firefox")) { //create firefox instance driver = new FirefoxDriver(); //Check if parameter passed as 'chrome' } else if (browser.equalsIgnoreCase("chrome")) {
  • 50. // specify the located driver.exe path by setProperty method System.setProperty("webdriver.chrome.driver","E:chromedriver_win32chromedr iver.exe"); //create chrome instance driver = new ChromeDriver(); } //Check if parameter passed as 'ie' else if (browser.equalsIgnoreCase("ie")) { // specify the located driver.exe path by setProperty method System.setProperty("webdriver.ie.driver", "E:IEDriverServer_Win32_2.39.0IEDriverServer.exe"); driver = new InternetExplorerDriver(); } else { throw new IllegalArgumentException("The Browser Type is Undefined"); } } @Test public void f() { driver.get("http://only-testing-blog.blogspot.in/2014/05/form.html"); driver.manage().window().maximize(); driver.findElement(By.xpath("//input[@name='FirstName']")).sendKeys("Rashed"); driver.findElement(By.xpath("//input[@name='LastName']")).sendKeys("mahmud"); driver.findElement(By.xpath("//input[@name='EmailID']")).sendKeys("fdf@gmail.c om); driver.findElement(By.xpath("//input[@name='MobNo']")).sendKeys("3343"); driver.findElement(By.xpath("//input[@name='Company']")).sendKeys("Brac It Services Ltd"); driver.findElement(By.xpath(".//*[@id='post-body- 8228718889842861683']/div[1]/form/input[6]")). submit(); } @AfterMethod public void afterMethod() { //driver.quit(); } }
  • 51. XML file configuration: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd"> <suite name="Suite" parallel="tests"> //for parallel testing <test name="FirefoxTest"> <parameter name="browser" value="firefox" /> //passing parameter: ‘browser’ <classes> <class name="automationFramework.TestNGMultiBrowser" /> //which class will be executed under package </classes> </test> <test name="ChromeTest"> <parameter name="browser" value="chrome" /> <classes> <class name="automationFramework.TestNGMultiBrowser" /> </classes> </test> <test name="IETest"> <parameter name="browser" value="ie" /> <classes> <class name="automationFramework.TestNGMultiBrowser" /> </classes> </test> </suite>
  • 52.
  • 53. Please follownext tutorial:Step –7: How to take a Screenshot In TestNG framework - Selenium Web Driver Step by step, I will share with you all different practice solution like previous. Please let me know feel free if you need to understand or share any suggestion or Problem regarding this step by Step tutorials SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 54. Step – 7: Taking a screenshot inSeleniumWebDriver –TestNG Framework At a glance, for better understanding before code practice I have used TakesScreenshot (one kind of Interface) for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver. Here, This getScreenshotAs() method takes argument of type OutputType.File so that it returns captured screenshot in File type. Like, For File type: File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE); getScreenshotsAs() method is used to take a screenshot. Now its time to copy and save this file somewhere in your file system or in your PC. For this purpose I have used copyFile() method of the FileUtils class from the org.apache.commons.io.FileUtils class. FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot3.png"), true); Here, “D:seleniumscreenshot3.png” screenshot saving path and screenshot will save as name screenshot3 in png format. Noted that you can use any format oryour choice path. Here, copyFile is a method of Class FileUtils and to call this method we need to write class.method() and in above code copyFile is taking argument from getScreenShotsAs() and new location where we want to save this captured Screenshot with name and with extension.
  • 55. Following code to execute for taking screenshot inTestNG Framework: package automationFramework; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.testng.annotations.AfterMethod; public class ScreenshotTestNG { WebDriver driver = new FirefoxDriver(); @Test public void TakingScreenShot() throws IOException { // Take screenshot and store it as a file format try { File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Copy and save the screenshot name (screenshot1.png) in below desired path using copyFile method FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot3.png"), true); System.out.println("Taken screenshot successfully"); } catch (IOException e) { System.out.println(e.getMessage()); } } @BeforeMethod public void beforeMethod() { // Wait For Page To Load //driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  • 56. //Get application driver.get("http://www.facebook.com/"); // Maximize Window driver.manage().window().maximize(); } @AfterMethod public void afterMethod() { driver.quit(); } }
  • 57. Using only Eclipse (not for TestNG framework): package automationFramework; import java.io.File; import java.io.IOException; import java.util.concurrent.TimeUnit; import org.apache.commons.io.FileUtils; import org.openqa.selenium.OutputType; import org.openqa.selenium.TakesScreenshot; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class Screen_shot { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub WebDriver driver = new FirefoxDriver(); // Wait For Page To Load driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); // Go to URL driver.get("http://www.facebook.com/"); // Maximize Window driver.manage().window().maximize(); // Take screenshot and store it as a file format File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE); // Copy and save the screenshot name (screenshot1.png) in below desired path using copyFile method FileUtils.copyFile(scrFile, new File("D:seleniumscreenshot1.png"), true); // Close Driver driver.quit(); } }
  • 58.
  • 59. Please follow next tutorial: Step – 8: How to handle Pop Up Alert, Conformation Alert And Prompt alert On TestNG framework - Selenium Web Driver Step by step, I will share with you all different practice solution like previous. Please let me know feel free if you need to understand or share any suggestion or Problem regarding this step by Step tutorials SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!
  • 60. Step – 8: How to handle simple alert popup, ConformationPop Up and Prompt Pop Up in SeleniumWebDriver –TestNG Framework At a glance, for better understanding before code practice Alertisa pop upwindowthatcomesup on screen. T here has some alertpopup such as:  Simple Alertpopup  ConformationAlert PopUp  PromptAlertPopUp Confirmationpopupisalsoa type of alertpopup. The differencebetweenalertpopup , confirmation popup and promptpop up is that alertpopup containssingle button ,confirmationpopupcontains twobuttons“OK” and “CANCEL”whereas promptpopup containsingle inputvalue field, twobuttons “OK” and “CANCEL”. Simple Alertpop up
  • 61. ConformationAlert Pop Up Prompt Alert Pop Up At a glance  Save HTML code as (.html) format in your PC thenspecifythis URL to getapplication pop up by driver.get(“…..”) incode.  driver.switchTo().alert(); -- to get alertpop up  I have usedaccept () methodto clickon OK button and dismiss() method for CANCEL.  sendKeys("Rashed"); -- To sendinput value
  • 62. Let’s practice fromhere stepby step for three (3) all: Simple Alert Pop Up: An alertbox isusedif anyone wantsto make sure informationcomesthroughtothe user. Firstly,Save below HTMLcode as (.html) formatwhichwill displays simplealertpopup withok button. Afterthat,we will automate it. Copy belowhtml code and save as an html file inyour PC: <html> <head> <title>Hi Rashed!Alertpopup </title> </head> <body> <h2> Rashed! AlertPopUp </h2> <fieldset> <legend>AlertBox</legend><p>Clickthe buttontodisplayanalertbox.</p> <buttononclick="alertFunction()">Clickonme</button> <script> functionalertFunction() {
  • 63. alert("Iaman example foralertbox!"); } </script> </fieldset> </body> </html>  Notedthatif youclickon alert.html thensimple alertpopupwill show (foryourbetter understanding). Following code to execute for Simple AlertPop upin TestNG Framework: package PopUpTestNG; // Import this package to handle the web based alerts in Web Driver. import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class alertTestNG { WebDriver driver=new FirefoxDriver(); @Test public void PopUpAlert() throws InterruptedException { //To maximize the window driver.manage().window().maximize(); //Specified Path to get the application where I have saved the HTML code, you use saved path from your PC driver.get("file:///D:/Selenium Web Driver Practice/popuppractice/alert.html");
  • 64. Thread.sleep(2000); //Click on ‘Click on me’ button driver.findElement(By.xpath("html/body/fieldset/button")).click(); Thread.sleep(2000); //To get alert pop up window Alert PopUpAlert = driver.switchTo().alert(); //To get alert Pop up text String alertText = PopUpAlert.getText(); //To show text as output System.out.println("Alert text is " + alertText); //To click on OK button and accept alert pop up PopUpAlert.accept(); } } Conformation Alert pop up: A confirmbox isusedif anyone wantthe userto verifyoraccept something. Secondly,Save belowHTML code as (.html) format whichwill displays confirmation popupwithok and Cancel button. Afterthat,we will automate it. Copy belowcode and save as an html file inyour PC: <html> <head> <title>Hi Rashed! ConfirmpopupSample </title> </head>
  • 65. <body> <h2> Rashed! Confirmpopup</h2> <fieldset> <legend>RashedConfirmBox</legend> <p>Clickthe buttonto displaya confirmbox.</p> <buttononclick="confirmFunction()">Clickonme</button> <p id="confirmdemo"></p> <script> functionconfirmFunction() { var cb; var c=confirm("Iaman Example forConfirmBox.nPress anybutton!"); if (c==true) { cb="You ClickedonOK!"; } else {
  • 66. cb="You ClickedonCancel!"; } document.getElementById("confirmdemo").innerHTML=cb; } </script> </fieldset> </body> Following code to execute for Conformation Popup in TestNG Framework: package PopUpTestNG; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class ConfirmPopUpTestNG { WebDriver driver=new FirefoxDriver(); @Test public void ConfirmPopUp() throws InterruptedException { driver.manage().window().maximize(); //Specified Path to get the application where I have saved the HTML code driver.get("file:///D:/Selenium Web Driver Practice/popuppractice/ConfirmPopUp.html"); Thread.sleep(2000); driver.findElement(By.xpath("html/body/fieldset/button")).click(); Thread.sleep(2000);
  • 67. //To switch or get conformation pop up Alert confirmationAlert = driver.switchTo().alert(); String alertText = confirmationAlert.getText(); System.out.println("Alert text is " + alertText); // use anyone(OK or Cancel) as per your need //To accept alert or click on Ok button confirmationAlert.accept(); //To cancel alert or click on Cancel button confirmationAlert.dismiss(); } } Prompt Alert: A promptbox is usedif anyone wantsthe userto inputa value before enteringapage. Thirdly,Save below HTMLcode as (.html) format whichwilldisplayspromptpopup withaninputvalue field,ok andCancel button. Afterthat,we will automate it. Copy belowcode and save as an html file inyour PC: <html> <head> <title>Hi Rashed!Here isa PromptpopupSample </title> </head> <body> <h2> Hi Rashed!PromptPopUp</h2>
  • 68. <fieldset> <legend>PromptBox</legend> <p>Clickthe buttonto demonstrate the promptbox.</p> <buttononclick="promptFunction()">Clickonme</button> <p id="promptdemo"></p> <script> functionpromptFunction() { var x; var person=prompt("Please enteryourname","Yourname"); if (person!=null) { x="Hello"+ person+ "! Welcome to Rashed.."; document.getElementById("promptdemo").innerHTML=x; } } </script> </fieldset> </body> </html>
  • 69. Following code to execute for Prompt Pop up in TestNG Framework: package PopUpTestNG; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; public class PromptPopUp { WebDriver driver=new FirefoxDriver(); @Test public void PromptPopUp() throws InterruptedException { driver.manage().window().maximize(); //Specified Path to get the application where I have saved the HTML code driver.get("file:///D:/Selenium Web Driver Practice/popuppractice/PromptPopUp.html"); Thread.sleep(2000); driver.findElement(By.xpath("html/body/fieldset/button")).click(); Thread.sleep(2000); Alert PromptnAlert = driver.switchTo().alert(); // Get Prompt pop up and send value by sendkeys() driver.switchTo().alert().sendKeys("Rashed"); //To accept prompt pop up or click on ok button PromptnAlert.accept(); //System.out.println(PromptnAlert.getText()); //To Cancel prompt pop up or click on Cancel button //PromptnAlert.dismiss(); } }
  • 70. Please follow next tutorial: Step – 9: How to upload/download a file On TestNG framework - Selenium Web Driver Step by step, I will share with you all different practice solution like previous. Please let me know feel free if you need to understand or share any suggestion or Problem regarding this step by Step tutorials SeleniumWebDriver tutorial is prepared &presented by Rashedul Islam(Rashed) BRAC It Services Ltd Best of Luck!