Webdriver (Selenium ) Interview Questions and answers
Question 1: What is Selenium 2.0
Answer: Webdriver is open source automation tool for web application. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.
Question 2: What is cost of webdriver, is this commercial or open source.
Answer: selenium is open source and free of cost.
Question 3: how you specify browser configurations with Selenium 2.0?
Answer: Following driver classes are used for browser configuration
Answer: Webdriver is open source automation tool for web application. WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.
Question 2: What is cost of webdriver, is this commercial or open source.
Answer: selenium is open source and free of cost.
Question 3: how you specify browser configurations with Selenium 2.0?
Answer: Following driver classes are used for browser configuration
·
AndroidDriver,
·
ChromeDriver,
·
EventFiringWebDriver,
·
FirefoxDriver,
·
HtmlUnitDriver,
·
InternetExplorerDriver,
·
IPhoneDriver,
·
IPhoneSimulatorDriver,
·
RemoteWebDriver
Question 4: How is Selenium 2.0 configuration different
than Selenium 1.0?
Answer: In case of Selenium 1.0 you need Selenium jar file pertaining to one library for example in case of java you need java client driver and also Selenium server jar file. While with Selenium 2.0 you need language binding (i.e. java, C# etc) and Selenium server jar if you are using Remote Control or Remote WebDriver.
Question5: Can you show me one code example of setting Selenium 2.0?
Answer: below is example
Answer: In case of Selenium 1.0 you need Selenium jar file pertaining to one library for example in case of java you need java client driver and also Selenium server jar file. While with Selenium 2.0 you need language binding (i.e. java, C# etc) and Selenium server jar if you are using Remote Control or Remote WebDriver.
Question5: Can you show me one code example of setting Selenium 2.0?
Answer: below is example
WebDriver
driver = new FirefoxDriver();
driver.get("https://www.google.co.in/");
driver.findElement(By.cssSelector("#gb_2
> span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1
> span.gbts")).click();
driver.findElement(By.cssSelector("#gb_8
> span.gbts")).click();
driver.findElement(By.cssSelector("#gb_1
> span.gbts")).click();
Question 6: Which web driver implementation is fastest?
Answer: HTMLUnitDriver. Simple reason is HTMLUnitDriver does not execute tests on browser but plain http request – response which is far quick than launching a browser and executing tests. But then you may like to execute tests on a real browser than something running behind the scenes
Question 7: What all different element locators are available with Selenium 2.0?
Answer: Selenium 2.0 uses same set of locators which are used by Selenium 1.0 – id, name, css, XPath but how Selenium 2.0 accesses them is different. In case of Selenium 1.0 you don’t have to specify a different method for each locator while in case of Selenium 2.0 there is a different method available to use a different element locator. Selenium 2.0 uses following method to access elements with id, name, css and XPath locator –
driver.findElement(By.id("HTMLid"));
driver.findElement(By.name("HTMLname"));
driver.findElement(By.cssSelector("cssLocator"));
driver.findElement(By.
className ("CalssName”));
driver.findElement(By.
linkText ("LinkeText”));
driver.findElement(By.
partialLinkText ("PartialLink”));
driver.findElement(By.
tagName ("TanName”));
driver.findElement(By.xpath("XPathLocator));
Question 8: How do I submit a form using Selenium?
Answer:
WebElement
el = driver.findElement(By.id("ElementID"));
el.submit();
Question 9: How to capture screen shot in Webdriver?
Answer:
File
file= ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(file,
new File("c:\\name.png"));
Question 10: How do I clear content of a text box in
Selenium 2.0?
Answer:
WebElement
el = driver.findElement(By.id("ElementID"));
el.clear();
Question 11: How to execute java scripts function.
Answer:
JavascriptExecutor
js = (JavascriptExecutor) driver;
String
title = (String) js.executeScript("pass your java scripts");
Question 12: How to select a drop down value using
Selenium2.0?
Answer: See point 16 in below post:
Question 13: How to automate radio button in Selenium 2.0?
Answer:
WebElement
el = driver.findElement(By.id("Radio button id"));
//to
perform check operation
el.click()
//verfiy
to radio button is check it return true if selected else false
el.isSelected()
Question 14: How to capture element image using Selenium
2.0?
Question 15: How to count total number of rows of a table
using Selenium 2.0?
Answer:
List
{WebElement} rows =
driver.findElements(By.className("//table[@id='tableID']/tr"));
int
totalRow = rows.size();
Question 16: How to capture page title using Selenium
2.0?
Answer:
String
title = driver.getTitle()
Question 17: How to store page source using Selenium
2.0?
Answer:
String
pagesource = driver.getPageSource()
Question 18: How to store current url using selenium 2.0?
Answer:
String
currentURL = driver.getCurrentUrl()
Question 19: How to assert text assert text of webpage using selenium 2.0?
Answer:
WebElement
el = driver.findElement(By.id("ElementID"));
//get
test from element and stored in text variable
String
text = el.getText();
//assert
text from expected
Assert.assertEquals("Element
Text", text);
Question 20: How to get element attribute using Selenium
2.0?
Answer:
WebElement
el = driver.findElement(By.id("ElementID"));
//get
test from element and stored in text variable
String
attributeValue = el. getAttribute("AttributeName") ;
Question 21: How to double click on element using selenium
2.0?
Answer:
WebElement
el = driver.findElement(By.id("ElementID"));
Actions
builder = new Actions(driver);
builder.doubleClick(el).build().perform();
Question 22: How to perform drag and drop in selenium 2.0?
Answer:
WebElement
source = driver.findElement(By.id("Source ElementID"));
WebElement
destination = driver.findElement(By.id("Taget
ElementID"));
Actions
builder = new Actions(driver);
builder.dragAndDrop(source,
destination ).perform();
Question 23: How to maximize window using selenium 2.0?
Answer:
driver.manage().window().maximize();
Question 24: How to verify pdf content using selenium 2.0?
Answer: Go through below post:
Road to verify 200 response code of web application in java
webdriver
This post will help to
verify HTTP response code 200 of web application using java webdriver. As
webdriver does not support direct any function to verify page response code.
But using "WebClient" of HtmlUnit API we can achieve this.
Html unit API is GUI less browser for java developer, using WebClent class we can send request to application server and verify response header status.
Below code, I used in my webdriver script to verify response 200 of web application
Html unit API is GUI less browser for java developer, using WebClent class we can send request to application server and verify response header status.
Below code, I used in my webdriver script to verify response 200 of web application
String
url = "http://www.google.com/";
WebClient
webClient = new WebClient();
HtmlPage
htmlPage = webClient.getPage(url);
//verify
response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
If HTTP authentication
is required in web application use below code.
String
url = "Application Url";
WebClient
webClient = new WebClient();
DefaultCredentialsProvider
credential = new DefaultCredentialsProvider();
//Set
some example credentials
credential.addCredentials("UserName",
"Passeord");
webClient.setCredentialsProvider(credential);
HtmlPage
htmlPage = webClient.getPage(url);
//verify
response
Assert.assertEquals(200,htmlPage.getWebResponse().getStatusCode());
Assert.assertEquals("OK",htmlPage.getWebResponse().getStatusMessage());
Road to verify images using java webdriver
In
this post I have explained that how to verify images in webdriver using java.
As webdriver does not provide direct any function to image verification, but we
can verify images by taking two screen shots of whole web page using
“TakesScreenshot” webdriver function, one at script creation time and another
at execution time,
In
below example I have created a sample script in which first I captured a Google
home page screen shot and saved (GoogleInput.jpg) into my project, Another
screen shot “GoogleOutput.jpg” captured of same page at test executing time and
saved into project. I compared both images if they are not same then test will
script fail.
Here
is sample code for same
package
com.test;
import
java.awt.image.BufferedImage;
import
java.awt.image.DataBuffer;
import
java.io.File;
import
java.io.IOException;
import
java.util.concurrent.TimeUnit;
import
javax.imageio.ImageIO;
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.Assert;
import
org.testng.annotations.AfterSuite;
import
org.testng.annotations.BeforeSuite;
import
org.testng.annotations.Test;
public
class ImageComparison {
public WebDriver driver;
private String baseUrl;
@BeforeSuite
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.co.in/";
driver.manage().timeouts().implicitlyWait(30,
TimeUnit.SECONDS);
}
@AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void testImageComparison()
throws IOException, InterruptedException
{
driver.navigate().to(baseUrl);
File screenshot = ((TakesScreenshot)driver).
getScreenshotAs(OutputType.FILE);
Thread.sleep(3000);
FileUtils.copyFile(screenshot, new File("GoogleOutput.jpg"));
File fileInput = new File("GoogleInput.jpg");
File fileOutPut = new File("GoogleOutput.jpg");
BufferedImage bufileInput = ImageIO.read(fileInput);
DataBuffer dafileInput = bufileInput.getData().getDataBuffer();
int sizefileInput =
dafileInput.getSize();
BufferedImage bufileOutPut = ImageIO.read(fileOutPut);
DataBuffer dafileOutPut = bufileOutPut.getData().getDataBuffer();
int sizefileOutPut = dafileOutPut.getSize();
Boolean matchFlag = true;
if(sizefileInput == sizefileOutPut)
{
for(int j=0; j<sizefileInput; j++) {
if(dafileInput.getElem(j) != dafileOutPut.getElem(j)) {
matchFlag = false;
break;
}
}
}
else
matchFlag = false;
Assert.assertTrue(matchFlag, "Images are not
same");
}
}
Road to handle http authentication in webdriver
One of my applications
had Http authentication for security purpose and I had need to automate using
webdriver. As we know http authentication is not a part of DOM object so we
cannot handle it using webdriver. Here is approach to handle such type situation.
We need to pass http credential with URL to skip http popup authentication window. Below is URL format.
We need to pass http credential with URL to skip http popup authentication window. Below is URL format.
User
above formatted URL in webdriver get method:
After using above approach, http authentication popup window disappear. But in Internet explorer, it raise error with message “wrong format url”. To accept same type url in internet explorer browser we need to add a DWORD value named exploere.exe and iexplore.exe with value data 0 in below registry.
To open registry, open "regeidt" from run command.
1.
For all users of the program, set the value in the following
registry key: HKEY_LOCAL_MACHINE\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
2.
For the current user of the program only, set the value in the
following registry key: HKEY_CURRENT_USER\Software\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
3.
If you are using 64 bit machine, set the value in the following
registry key. HKEY_CURRENT_USER\Software\WOW6432Node\Microsoft\Internet
Explorer\Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
Road to automate Html5 video with Webdriver (Selenium)
In
this post I will show you how to automate HTML5 video. To automate this
we will use java scripts function to control video. So here we use “document.getElementById("Video
ID")” , it return the HTML 5 video object. Using this object we can
simulate video. Following are some java script function to handle video.
1. Play video
1. Play video
document.getElementById("Video ID").play();
2. Pause video
document.getElementById("Video ID").pause() ;
3.
To check video is paused or not use below code
document.getElementById("Video ID").Paused;
4.
To increase volume
document.getElementById("Video ID").volume=0.5;
5.
To reload video
document.getElementById("Video ID").load();
6.
To replay from stating or forward and back playing video. You can set current
playing time.
document.getElementById("Video ID").currentTime=0
document.getElementById("Video ID").currentTime=10
document.getElementById("Video ID").currentTime=20
7.
To check video is muted.
document.getElementById("Video ID").muted
Example: here is example of Webdriver to automate html 5 video, I am using JavascriptExecutor class to execute java script code.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
public class HtmlVideo {
public WebDriver driver;
@Test
public void testVideo() throws
InterruptedException
{
driver
= new FirefoxDriver();
driver.manage().window().maximize();
JavascriptExecutor
js = (JavascriptExecutor) driver;
//play
video
js
.executeScript("document.getElementById(\"video\").play()");
Thread.sleep(5000);
//pause
playing video
js
.executeScript("document.getElementById(\"video\").pause()");
//check
video is paused
System.out.println(js
.executeScript("document.getElementById(\"video\").paused"));
js
.executeScript("document.getElementById(\"video\").play()");
//
play video from starting
js
.executeScript("document.getElementById(\"video\").currentTime=0");
Thread.sleep(5000);
//reload
video
js
.executeScript("document.getElementById(\"video\").load()");
}
}
|
Screen Recording (Video) of Java Webdriver script
Sauce
lab provided screen capturing functionality to test scripts execution, I was
looking same type functionality to work on local machine and came up across “Monte Media Library” java based library developed by Werner
Randelshofer.. In this post I have described a way to capture screen cast/
Video recording of selenium/webdriver test script execution.
Step to implement Monte Media library to selenium/Webdriver test scripts.
Step to implement Monte Media library to selenium/Webdriver test scripts.
1.
Download “MonteScreenRecorder.jar” from link
http://www.randelshofer.ch/monte/
2.
Add this jar file to your selenium/webdriver eclipse project.
3.
This jar file contain “ScreenRecorder” class, we need to create
this class object by following way.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
GraphicsConfiguration
gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
ScreenRecorder
screenRecorder = new
ScreenRecorder(gc,
new Format(MediaTypeKey,
MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey,
ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
DepthKey,
24, FrameRateKey, Rational.valueOf(15),
QualityKey,
1.0f, KeyFrameIntervalKey, 15 * 60),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, "black",
FrameRateKey,
Rational.valueOf(30)),null);
|
4. Need to call “screenRecorder.start()” methods at starting of your test scripts and
"screenRecorder.stop()” at the end of execution.
5. Below
is complete test script example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
package
com.TestScripts;
import
java.awt.*;
import
java.io.File;
import
org.monte.media.Format;
import
org.monte.media.math.Rational;
import
org.monte.screenrecorder.ScreenRecorder;
import
org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
static org.monte.media.AudioFormatKeys.*;
import
static org.monte.media.VideoFormatKeys.*;
public class VideoReord {
private ScreenRecorder screenRecorder;
public static void main(String[] args) throws Exception {
VideoReord
videoReord = new VideoReord();
videoReord.startRecording();
WebDriver
driver = new FirefoxDriver();
WebElement
element =
driver.findElement(By.name("q"));
element.sendKeys("testing");
element.submit();
System.out.println("Page
title is: " +driver.getTitle());
driver.quit();
videoReord.stopRecording();
}
public void startRecording() throws
Exception
{
GraphicsConfiguration
gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
this.screenRecorder
= new ScreenRecorder(gc,
new Format(MediaTypeKey,
MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey,
ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
DepthKey,
24, FrameRateKey, Rational.valueOf(15),
QualityKey,
1.0f,
KeyFrameIntervalKey,
15 * 60),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, "black",
FrameRateKey,
Rational.valueOf(30)),
null);
this.screenRecorder.start();
}
public void stopRecording() throws
Exception
{
this.screenRecorder.stop();
}
}
|
6. After execution test script, video file is generated under “Video”
folder of current user folder in Windows machine and “Movies” folder on
Mac machine.
I am getting some comments for saving video in a desire location, I am going to update my post as Michael’s suggestion. Thanks again for his help.
If you need to save video file in desire location, then you need to override “createMovieFile” function of “ScreenRecorder” class class for creating a new folder and file. For this you need to create another class like “SpecializedScreenRecorder” and extend “ScreenRecorder” class as below:
I am getting some comments for saving video in a desire location, I am going to update my post as Michael’s suggestion. Thanks again for his help.
If you need to save video file in desire location, then you need to override “createMovieFile” function of “ScreenRecorder” class class for creating a new folder and file. For this you need to create another class like “SpecializedScreenRecorder” and extend “ScreenRecorder” class as below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
package
com.test;
import
java.awt.AWTException;
import
java.awt.GraphicsConfiguration;
import java.awt.Rectangle;
import
java.io.File;
import
java.io.IOException;
import
java.text.SimpleDateFormat;
import
java.util.Date;
import
org.monte.media.Format;
import
org.monte.media.Registry;
import
org.monte.screenrecorder.ScreenRecorder;
public class SpecializedScreenRecorder extends ScreenRecorder {
private String name;
public SpecializedScreenRecorder(GraphicsConfiguration
cfg,
Rectangle
captureArea, Format fileFormat, Format screenFormat,
Format
mouseFormat, Format audioFormat, File movieFolder,
String
name) throws IOException, AWTException {
super(cfg,
captureArea, fileFormat, screenFormat, mouseFormat,
audioFormat,
movieFolder);
this.name
= name;
}
@Override
protected File createMovieFile(Format
fileFormat) throws IOException {
if (!movieFolder.exists()) {
movieFolder.mkdirs();
}
else if (!movieFolder.isDirectory()) {
throw new IOException("\"" + movieFolder + "\" is not a directory.");
}
SimpleDateFormat
dateFormat = new SimpleDateFormat(
"yyyy-MM-dd
HH.mm.ss");
return new File(movieFolder, name + "-" + dateFormat.format(new Date()) + "."
+
Registry.getInstance().getExtension(fileFormat));
}
}
|
Now
you need to create object of “SpecializedScreenRecorder” instead of
creating “Screen” class object.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
|
package
com.test;
import
java.awt.*;
import
java.io.File;
import
org.monte.media.Format;
import
org.monte.media.math.Rational;
import
org.monte.screenrecorder.ScreenRecorder;
import
org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
static org.monte.media.AudioFormatKeys.*;
import
static org.monte.media.VideoFormatKeys.*;
public class VideoReord {
private ScreenRecorder screenRecorder;
public static void main(String[] args) throws Exception {
VideoReord
videoReord = new VideoReord();
videoReord.startRecording();
WebDriver
driver = new FirefoxDriver();
WebElement
element =
driver.findElement(By.name("q"));
element.sendKeys("testing");
element.submit();
System.out.println("Page
title is: " +
driver.getTitle());
driver.quit();
videoReord.stopRecording();
}
public void startRecording() throws
Exception
{
File
file = new File("D:\\Videos");
Dimension
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int
width = screenSize.width;
int
height = screenSize.height;
Rectangle
captureSize = new Rectangle(0,0,
width, height);
GraphicsConfiguration
gc = GraphicsEnvironment
.getLocalGraphicsEnvironment()
.getDefaultScreenDevice()
.getDefaultConfiguration();
this.screenRecorder
= new SpecializedScreenRecorder(gc,
captureSize,
new Format(MediaTypeKey,
MediaType.FILE, MimeTypeKey, MIME_AVI),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
CompressorNameKey,
ENCODING_AVI_TECHSMITH_SCREEN_CAPTURE,
DepthKey,
24, FrameRateKey, Rational.valueOf(15),
QualityKey,
1.0f,
KeyFrameIntervalKey,
15 * 60),
new Format(MediaTypeKey,
MediaType.VIDEO, EncodingKey, "black",
FrameRateKey,
Rational.valueOf(30)),
null,
file, "MyVideo");
this.screenRecorder.start();
}
public void stopRecording() throws
Exception
{
this.screenRecorder.stop();
}
}
|
Above code explanation: Create a File class object and pass path where you want to save
your video
File file = new File("D:\\Videos");
Create
dimension of your screen to capture video, I have created object for default
screen.
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int width = screenSize.width;
int height = screenSize.height;
Rectangle captureSize = new Rectangle(0,0, width, height);
Now
Create object of “SpecializedScreenRecorder” and pass Rectangle object, File
object, and file name as a last argument and rest are same.
Run your test, you will see that a video will generate under your desire location.
Run your test, you will see that a video will generate under your desire location.
Road to verify PDF file text using java webdriver
In this post I will
explain the procedure to verify PDF file content using java webdriver. As
some time we need to verify content of web application pdf file, opened in
browser.
Use below code in your test scripts to get pdf file content.
Use below code in your test scripts to get pdf file content.
//get
current urlpdf file url
URL
url = new URL(driver.getCurrentUrl());
//create
buffer reader object
BufferedInputStream
fileToParse = new BufferedInputStream(url.openStream());
PDFParser
pdfParser = new PDFParser(fileToParse);
pdfParser.parse();
//save
pdf text into strong variable
String
pdftxt = new PDFTextStripper().getText(pdfParser.getPDDocument());
//close
PDFParser object
pdfParser.getPDDocument().close();
After
applying above code, you can store all pdf file content into “pdftxt” string
variable. Now you can verify string by giving in put. As if you want to verify “Selenium Or
Webdiver” text. Use below code.
Assert.assertTrue(pdftxt.contains(“Selenium
Or Webdiver”))
Hope
this post will help to verify web application PDF content.
Road to publish Webdriver TestNg report in Jenkins
In this post I will
show you how to publish TestNg report on Jenkins server.
Installation TestNG plug-in.
1. After launching Jenkins server go to "Manage Jenkins>>Manage Plugins"
2. Enter TestNg in filter field, you will see “TestNg Results Plugin” like below screen.
Installation TestNG plug-in.
1. After launching Jenkins server go to "Manage Jenkins>>Manage Plugins"
2. Enter TestNg in filter field, you will see “TestNg Results Plugin” like below screen.
3.
Click on check box and then click on installation button.
Setup Job:
Create
new job in Jenkins by following below steps. In this I am integrating
Webdriver TestNg suite with Ant build tool.
1.
Go to Jenkins home page and click on “New Item”
2.
Enter item name, select check box as per your requirement and click on OK
button.
3.
Enter required field, As I am using ant tool so I click on “Add Build steps”
and select “Invoke Ant”
4.
Enter target name.
5.
Click on “Add post Build Action” and select “Publish TestNG Results” option.
6.
Change TestNg report file name if you have not default.
7.
Click “Apply“ and “Save” button.
8.
Go to your created Job you should see “TestNg Result” link.
9.
Put your entire code base into created Job's workspace.
Execution and Report:
1.
Build your job.
2.
Click on “TestNg Result” link you will show report like below:
3.Click
on build link for testng report, like above “Build #3” you should see published
report.
How to Set up and launching Selenium Grid?
Download selenium
latest jar file from Webdriver
Launching Hub:
Open command prompt and got to your selenium server jar file and run command:
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 4444 -role hub
screen should be displayed like below.
Launching Hub:
Open command prompt and got to your selenium server jar file and run command:
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 4444 -role hub
screen should be displayed like below.
Launching Nodes:
Open two command prompt and go to your selenium server jar file and run below command:
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5555 -role webdriver -hub http://localhost:4444/grid/register -browser browserName=firefox,platform=WINDOWS,version=13
java -jar selenium-server-standalone-2.21.0.jar -host localhost -port 5556 -role webdriver -hub http://localhost:4444/grid/register -browser browserName=firefox,platform=XP,version=12
Screen should be displayed like below:
Note: if you want to run Node on different machine then replace “localhost” to your system IP address where Hub is running.
Open Url :localhost:4444/console” you will see like below screen.
How to run python webdriver test scripts using Grid2
Prerequisite:
1.
Java and python should be installed and setup path in your
machine..
2.
Download xmlrunner.py from below url:
http://pypi.python.org/pypi/XmlTestRunner/0.16654
3.
Download and install “setuptools 0.6c11” from below link:
http://pypi.python.org/pypi/setuptools
4.
Install selenium 2 in your system using command: >
easy_install selenium
5.
Selenium server file should be in machine
Set up and launching Selenium Grid:
1. Run below command in on your console to launch Grid hub console:
1. Run below command in on your console to launch Grid hub console:
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 4444 -role hub
2. Open two console and run below command to launch and register node with Grid
hub.
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 5555 -role webdriver -hub http://localhost:4444/grid/register
-browser browserName=firefox,platform=WINDOWS
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 5556 -role webdriver -hub
http://192.168.1.22:4444/grid/register -browser
browserName=iexplore,platform=WINDOWS
Replace local host to system IP of Hob machine. If you want to launch node in
different machine.
Test script::
Put “xmlrunner.py” downloaded file in your project and create a scripts as like below script.
Test script::
Put “xmlrunner.py” downloaded file in your project and create a scripts as like below script.
from selenium import webdriver
import unittest
import sys
from xmlrunner import *
class Grid2(unittest.TestCase):
capabilities = None
def
setUp(self):
self.driver =
webdriver.Remote(desired_capabilities={
"browserName": browser,
"platform":platform,
"node":port
})
print "set up executed"
def test_example(self):
self.driver.get("http://www.google.com")
print "open google url"
self.assertEqual(self.driver.title,
"Google")
print "verify title"
self.driver.find_element_by_id("gbqfq").clear()
self.driver.find_element_by_id("gbqfq").send_keys("testing")
print "enter text in serach
field"
self.driver.find_element_by_id("gbqfb").click()
print "click on search
button"
def tearDown(self):
self.driver.quit()
if __name__ == "__main__":
args = sys.argv
port = args[1]
platform = args[2]
browser = args[3]
suite = unittest.TestSuite()
suite.addTest(Grid2('test_example'))
runner =
XMLTestRunner(file('results_ExampleTestCase_%s.xml' % (browser),
"w"))
runner.run(suite)
Execution:
Open
two consoles go to your test scripts project and run below command one by one.
python Grid2.py 5555 WINDOWS firefox
python Grid2.py 5556 WINDOWS iexplore
Where Grid2.py is created test script.
After execution two xml files are generated under project for each execution.
How to run java test scripts using Grid2
Prerequisites.
1.
Java should be install and setup path in system.
2.
Eclipse should be configured TestNG plugin
3.
Download the selenium-server-standalone-version.jar from the
below location.
4.
TestNG jar file.
Steps to create and execute test scripts:
1.
Launch Grid 2 console(Hub ) and Nodes using below commands:
Hub:
java -jar selenium-server-standalone-2.29.0.jar -host
localhost -port 4444 -role hub
Nodes:
java -jar selenium-server-standalone-2.29.0.jar -host
localhost -port 5555 -role webdriver -hub http://localhost:4444/grid/register
-browser browserName=iexplore,platform=XP,version=8
java -jar selenium-server-standalone-2.29.0.jar -host
localhost -port 5556 -role webdriver -hub http://localhost:4444/grid/register
-browser browserName=firefox,platform=XP,version=13
2. Run
test case parallel: This “WebDriverGrid2Test “ example will be run test
case on firefox and internet explorer on version 8 and 13 respectively.
package com.test;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
public class WebDriverGrid2Test {
public WebDriver driver;
@Parameters({"browser",
"version", "os"})
@BeforeClass
public void setup(String browser, String
version, String os) throws MalformedURLException,
InterruptedException {
DesiredCapabilities capability=null;
capability = gridStting(browser, version, os);
driver = new RemoteWebDriver(new
URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to("http://google.com");
}
@Test
public void testGoogleSearch2() throws InterruptedException{
Thread.sleep(3000);
WebElement search_input =
driver.findElement(By.id("gbqfq"));
search_input.clear();
search_input.sendKeys("Testing");
WebElement search_button =
driver.findElement(By.id("gbqfb"));
search_button.click();
}
@Test
public void testGoogleSearch1(){
WebElement search_input = driver.findElement(By.id("gbqfq"));
search_input.clear();
search_input.sendKeys("Testing");
WebElement search_button =
driver.findElement(By.id("gbqfb"));
search_button.click();
}
@AfterClass
public void tearDown(){
driver.quit();
}
public DesiredCapabilities gridStting(String
browser, String version, String os){
DesiredCapabilities capability=null;
if(browser.equals("firefox")){
System.out.println("Test scripts running
on firefox");
capability= DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setVersion(version);
}
if(browser.equals("iexplore")){
System.out.println("Test scripts running
on iexplore");
capability=
DesiredCapabilities.internetExplorer();
capability.setBrowserName("iexplore");
System.setProperty("webdriver.ie.driver",
"IEDriverServer.exe");
capability.setVersion(version);
}
if(os.equals("WINDOWS")){
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
}
else if(os.equals("XP")){
capability.setPlatform(org.openqa.selenium.Platform.XP);
}
else if(os.equals("Linux")){
capability.setPlatform(org.openqa.selenium.Platform.LINUX);
}
else{
capability.setPlatform(org.openqa.selenium.Platform.ANY);
}
return capability;
}
}
3. We
need to create TestNG file like as below “Suite.xml” file:
<?xml version="1.0" encoding="UTF-8"?>
<?xml version="1.0" encoding="UTF-8"?>
<suite
name="Test case run on Two environment" verbose="3"
parallel="tests" thread-count="2">
<test name="Run on Internet Explorer">
<parameter
name="browser" value="iexplore"/>
<parameter name="version" value="8"/>
<parameter name="os" value="XP"/>
<classes>
<class
name="com.test.WebDriverGrid2Test"/>
</classes>
</test>
<test name="Run on Firefox">
<parameter name="browser"
value="firefox"/>
<parameter name="version" value="13"/>
<parameter name="os" value=" XP "/>
<classes>
<class
name="com.test.WebDriverGrid2Test"/>
</classes>
</test>
</suite>
4.
Rigth click on Suite.xml file, select “Run As” and click on TestNG
Suite options
5.
Now test script is executed on both browser and version combination.
execution log on eclipse look like as below:
.
Webdriver C# test scripts execution using Grid2
Nunit
framework is not support parallel execution of driver test scripts using Grid.
If we use MbUuit framework then we can accomplish parallel execution of test
scripts against Grid2. For set up MbUnit you can see “MbUnit Framework”
Test scripts setup :
Test scripts setup :
1.
Add reference Gallio and MbUnit ddl file to your Webdriver
project from installed Gallio folder.
2.
Add below code in project’s “AssemblyInfo.cs” file.
using MbUnit.Framework;
[assembly:DegreeOfParallelism(2)]
[assembly:Parallelizable(TestScope.All)]
3. We need to add below code for MbUnit framework in test
scripts.
using MbUnit.Framework;
add [Parallelizable] annotation on test case lavel ass I
added in belowtest scripts.
4. I have created two test one “GridTest1.cs” file for
internet explorer and “GridTest2.cs” file for firefox browser.
GrridTest1.cs
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MbUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
namespace SmapleProject
{
[Parallelizable]
[TestFixture]
public class GridTest1
{
private
IWebDriver driver;
private
StringBuilder verificationErrors;
private string
baseURL;
[SetUp]
public void
SetupTest()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities =
DesiredCapabilities.InternetExplorer();
capabilities.SetCapability(CapabilityType.BrowserName, "iexplore");
capabilities.SetCapability(CapabilityType.Platform, new Platform(PlatformType.Windows));
capabilities.SetCapability(CapabilityType.Version, "9.0");
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"),
capabilities);
baseURL = "https://www.google.co.in/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void
TeardownTest()
{
driver.Quit();
}
[Test]
public void
GoogleTest()
{
driver.Navigate().GoToUrl(baseURL + "/");
driver.FindElement(By.Id("gbqfq")).Clear();
driver.FindElement(By.Id("gbqfq")).SendKeys("Testing");
driver.FindElement(By.Id("gbqfb")).Click();
}
}
}
GridTest2.cs
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using MbUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Remote;
namespace SmapleProject
{
[Parallelizable]
[TestFixture]
public class GridTest2
{
private
IWebDriver driver;
private
StringBuilder verificationErrors;
private string
baseURL;
[SetUp]
public void
SetupTest()
{
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities = DesiredCapabilities.Firefox();
capabilities.SetCapability(CapabilityType.BrowserName, "firefox");
capabilities.SetCapability(CapabilityType.Platform, new
Platform(PlatformType.Windows));
capabilities.SetCapability(CapabilityType.Version, "15.0");
driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"),
capabilities);
//driver = new FirefoxDriver();
baseURL = "https://www.google.co.in/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void
TeardownTest()
{
driver.Quit();
}
[Test]
public void
GoogleTest()
{
driver.Navigate().GoToUrl(baseURL + "/");
driver.FindElement(By.Id("gbqfq")).Clear();
driver.FindElement(By.Id("gbqfq")).SendKeys("Testing");
driver.FindElement(By.Id("gbqfb")).Click();
}
}
}
Launch Grid
1. Run below command in on your console to launch Grid hub console:
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 4444 -role hub
2. Open two console and run below command to launch and register node with Grid hub.
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 5555 -role webdriver -hub http://localhost:4444/grid/register
-browser browserName=firefox,platform=WINDOWS
java -jar selenium-server-standalone-2.21.0.jar -host
localhost -port 5556 -role webdriver -hub
http://192.168.1.22:4444/grid/register -browser browserName=iexplore,platform=WINDOWS
Test Execution:
1. Build webdriver project.
2. Open Gallio Icarus console add created Webdriver project dll file.
3. Select both test script and click on run button. You should see both test case executed parallels.
No comments:
Post a Comment