Selenium Programming Cookbook PDF
Selenium Programming Cookbook PDF
ii
Contents
1.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.2
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1.3
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2
Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.3
Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
2.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
17
3.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2
3.3
3.4
3.5
3.6
29
4.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4.2
4.3
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
39
5.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
5.2
5.3
Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4
Run tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
5.5
iii
47
6.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
6.2
6.3
Integrate to JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
6.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
6.5
58
7.1
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
7.2
7.3
Usage cases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
7.4
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
7.5
iv
Preface
Selenium is a portable software testing framework for web applications. Selenium provides a record/playback tool for authoring
tests without learning a test scripting language (Selenium IDE). It also provides a test domain-specific language (Selenese) to
write tests in a number of popular programming languages, including Java, C#, Groovy, Perl, PHP, Python and Ruby.
The tests can then be run against most modern web browsers. Selenium deploys on Windows, Linux, and Macintosh platforms.
It is open-source software, released under the Apache 2.0 license, and can be downloaded and used without charge. (Source:
https://bit.ly/2bNZYaa)
In this ebook, we provide a compilation of Selenium programming examples that will help you kick-start your own projects. We
cover a wide range of topics, from Installation and JUnit integration, to Interview Questions and Standalone Server functionality.
With our straightforward tutorials, you will be able to get your own projects up and running in minimum time.
vi
1 / 65
Chapter 1
Introduction
In this tutorial, we are going to show how you can install the Selenium IDE, Selenium Server and Selenium WebDriver.
Selenium is the tool for automation testing web apps. Selenium consists from IDE, WebDrivers and Server.
The general scenery of testing in Selenium is to record the user activities by Selenium IDE and after that to run this tests cases
automatically. It uses two different approaches to execute the tests. One of them uses the native browser API, another uses the
injecting JavaScript codes to browsers. The main benefit about Selenium IDE is the ability to execute tests on varied browsers.
You can find the list of supported Selenium browsers below:
Firefox
IE
Safari
Opera
Google Chrome
Another great thing about Selenium is that you can export the tests cases to your favorite programming languages: Java, Ruby,
Python, C# and so on.
1.2
Installation
The installation process is very simple. Firstly, You should go to official web site seleniumhq.org.
2 / 65
3 / 65
4 / 65
5 / 65
6 / 65
1.3
Conclusion
In this tutorial, weve shown how to install the Selenium tools. As you saw this process is kindly simple. If you want to improve
your knowledge about Selenium, you can visit the official web site.
7 / 65
Chapter 2
Introduction
In this tutorial, we are going to show how you can test your web app by Selenium IDE. Selenium IDE is the Firefox plugin,
which can record the user browser action and run it automatically further. We are going to install the Selenium IDE, explain most
useful controlls and panels, record the simple use cases and run it automatically by Selenium IDE, add the schedule for tests,
export this test case to programming languages.
Selenium IDE has special commands. Selenium commands emulate user activities. You can emulate any user activities: insert the
text, submit the form, navigate in apps, click on link, click on checkbox, select the options in combobox. The main benefic about
Selenium IDE is that you dont need to have any experience in programming languages. All you need is install the Selenium
plugin, record the use activities and run the tests. It is so user-friendly. Selenium IDE uses the native browser API for testing, so
you can use all specters commands, which Firefox browser supports. Lets start to install the Selenium IDE.
2.2
Installation
First of all, we go to the download page and select the last version of Selenium ide there - https://docs.seleniumhq.
org/download/ .Download Selenium IDE Download Selenium IDE
After we downloaded this plugin, Firefox browser offers to install this addons. You need to allow this process. Selenium IDE is
installed and we can see the Selenium IDE button on the right-top corner in Firefox.
8 / 65
9 / 65
10 / 65
2.3
11 / 65
Testing
Lets imagine, that we need to test the searching function in this site - https://examples.javacodegeeks.com. First,
we should turn the record button on, put the base URL and go to main browser window. We go to this site, find the search input,
type the necessary text, submit the form. After that, we get the searching result and now we need to verify this result. We need
to select the necessary element and open the right mouse menu, as show below.
12 / 65
13 / 65
14 / 65
15 / 65
16 / 65
Selenium IDE can export your case tests to your favorite programming languages.
2.4
Conclusion
In this article, we show you how you can use Selenium IDE to test your web apps. Selenium IDE is the great tool for building
automations tests easily.
You can find more information about this tool on the official website link.
17 / 65
Chapter 3
Introduction
In this example, we shall show you how to write the automation tests by Selenium. Selenium is collections of tools to test the
web applications. We are going to cover users cases for TrackStudio system.
Automation tests has few benefits:
It is easy for supporting.
It is faster than manual tests.
It has possibility to repeat tests.
It has the lower cost with compare to manual tests.
It has ability to use in Continue Integration.
It has ability to get exhausted reports.
Selenium consists from three main parts:
Selenium IDE - add-ons for Firefox.
Selenium WebDriver - library, which use native browser API for testing.
Selenium Server - server for execute tests in different environments.
3.2
Before we start to write the tests code, we should write the tests plan. The plan should describe what we should do and what we
will expect after those actions. Lets tell few words about TrackStudio system. TrackStudio is issues/tasks tracker in the simple
words.
It supports: workflow processing, documents processing, access rules control and so on. It fits great for our demonstration
purpose, because it is the web app with rich user interfaces and it has many functional features.
Lets imagine that we want to test all cases for creating the library (books store) configuration in TrackStudio.
Table 3.1: Tests cases
18 / 65
Detail explanation
1. Go to index page. 2. Fill the login
form. 3. Submit the form.
4. Go to manage user tab 5. Open the
rules tab. 6. Click on the create button
7. Fill the form. 8. Submit the form.
1. Go to manage user tab 2. Open the
rules tab. 3. Click on the create button
4. Fill the form. 5. Submit the form.
1. Go to manage user tab 2. Open the
users tab. 3. Click on the create button
4. Fill the form. 5. Submit the form.
1. Go to manage user tab 2. Open the
users tab. 3. Click on the create button
4. Fill the form. 5. Submit the form.
1. Go to manage task tab. 2. Open the
workflow tab. 3. Click on the create
button. 4. Fill the form. 5. Submit the
form.
1. Go to manage task tab. 2. Open the
workflow tab. 3. Open the status tab.
4. Click on the create button. 5. Fill
the form. 6. Submit the form.
1. Go to manage task tab. 2. Open the
workflow tab. 3. Open the transaction
tab. 4. Selected the necessary status
and click on the create button.
1. Go to manage task tab. 2. Open the
category tab. 3. Click on the create
button. 4. Fill the form. 5. Submit the
form.
1. Go to manage task tab. 2. Click on
the new project button. 3. Fill the
form. 4. Submit the form.
1. Go to manage task tab. 2. Open the
access rule tab. 3. Selected the rules.
4. Submit the form.
1. Log out. 2. Log in as Bread. 3. Go
to the library project. 4. Click the new
book button. 5. Fill the form. 6.
Submit the form.
1. Log out. 2. Log in as Smith. 3. Go
to the library project. 4. Click the new
book link. 5. Click the out operation
button. 6. Fill form and submit it.
Expected result
Redirect to main page.
The rule should appear in rules list
3.3
First of all we should install the Selenium IDE. You should open the Firefox.Then you should go to official Selenium web site
link.
19 / 65
20 / 65
3.4
21 / 65
Firstly, we should run the TrackStudio Server. You should open the FireFox and open the URL https://localhost:8080/
TrackStudio/ It will look similar:
22 / 65
23 / 65
24 / 65
25 / 65
26 / 65
3.5
Now we have the source code on your tests cases. Then we should create the maven project with selenium dependency and put
there your test code.
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/ xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru</groupId>
<artifactId>parsentev</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.48.2</version>
</dependency>
</dependencies>
</project>
Now we can open our new project in Eclipse and make the refactoring. How you can see below the exported code does look
good. It has duplicates codes.
27 / 65
String
String
String
String
28 / 65
WORKFLOW_NAME = "book";
TASK_NAME = "the catcher in the rye";
TR_IN = "in";
TR_OUT = "out";
The next step is to split out main on the few little as we described in table tests ceases.
TrackStudioCreateLibraryConfiguration.java
@Test
public void cases() throws Exception {
this.loginAsAdmin();
this.createManagerRole();
this.createReaderRole();
this.createUserManager();
this.createUserReader();
this.createWorkflow();
this.createCategory();
this.createTask();
this.takeTaskByReader();
}
We have the automation tests, which you can run the follow command mvn clean test. You can integrate it to CI easily.
3.6
Download
You can download the full source code of this example here: SeleniumAutomationTests.zip
29 / 65
Chapter 4
Introduction
In this example we shall show the most popular interviews questions about Selenium tools and give you exhaustive answers.
Questions cover all topics:
Selenium 1
Selenium 2
Selenium IDE
Selenium Standalone Server
In this article is shown theoretical questions and best practices, which is used by Selenium communities.
4.2
What is Selenium?
Selenium is the complex of tools for automation testing the web applications. This tools is developed in Java. You can use
different approaches for create the tests: using Selenium IDE, using one of popular programming languages (Java, C#, Perl,
Python). Because right now web applications become very interactive it is to difficult to write automation tests for its. Selenium
uses two kind of approaches for doing it: directly using browser api (new version), injecting JavaScript (old version).
What modules does Selenium consist?
Selenium has few different modules:
Selenium IDE - firefox plugin, The plugin has two modes : records user activities, run the tests by user activities.
Selenium 1 (Selenium RC) - library, which converts the code to JavaScript and injects it to the browser.
Selenium 2 (Selenium WebDriver) - library, which uses the browser api for testing.
Selenium Server (Selenium Grid) - server. It is used to run tests in different environments.
What the technology is used for searching elements in Selenium?
Selenium is used DOM for searching elements. The DOM can look like the Tree Structure.
How to find different type of elements in Selenium, explain few different ways?
Lets consider this question by simple HTML example
index.html
30 / 65
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example page for Selenium Test</title>
</head>
<body>
<iframe name="tree" src="tree.html"></iframe>
<div class="form">
<form about="/" method="POST">
User name : <input name="username" type="text">
<a href="/agreements.html">User agreements</a>
</form>
</div>
</body>
</html>
31 / 65
Description :
<textarea name="desc"></textarea>
<input id="submit" type="button" value="Submit">
</form>
</body>
</html>
The main approach looks like : get necessary elements, fill the data.
/**
* Test filling the form with different input elements.
*/
public void fillForm() {
//fill the user name
driver.findElement(By.name("username")).sendKeys("Petr");
//checked agreement
driver.findElement(By.name("agreement")).click();
//choose sex
driver.findElements(By.name("sex")).get(0).click();
//select country
WebElement select = driver.findElement(By.tagName("select"));
select.findElements(By.tagName("option")).get(0).click();
//fill description
driver.findElement(By.name("desc")).sendKeys("Petr");
//push on button
driver.findElement(By.id("submit")).click();
}
32 / 65
33 / 65
34 / 65
java.util.regex.Pattern;
java.util.concurrent.TimeUnit;
org.junit.*;
static org.junit.Assert.*;
static org.hamcrest.CoreMatchers.*;
org.openqa.selenium.*;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.Select;
35 / 65
}
@Test
public void testJavaCodeGeeksTests() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("I reject the FREE eBooks")).click();
driver.findElement(By.cssSelector("span.foobar-close-button")).click();
new Select(driver.findElement(By.id("top-menu-mob"))).selectByVisibleText("regexp:\\s +-\\s+-\\sJava Tutorials");
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
36 / 65
So when you need to change the user credential, you go to this file and change only this code without searching all places where
you use it.
What is Page Object Pattern? How is it used in Selenium?
This pattern is used in automation tests overall. The main advantages are hiding the implementation of auth details and splitting
the all web apps tests on small undescended pages.
What is DDT and how is it supported in Selenium?
DDT is the data tests. Selenium does not have special mechanism for working with DDT. You can use another libraries for it.
For example, read data from database by JDBC, or read data from file and so on.
What is Selenium Grid? Where is it used?
Selenium Grid is distributed servers which offers to run tests in different enviroments.
How to execute the Selenium tests in parallel?
It can be done by Selenium Gird or by using Thread in Java directly.
What kind of problems do you have when using Selenium?
First, it is not so faster to change the automation tests when UI in web app can be changed faster. However, these problems have
all automation testing tools. Another problem is appear in dynamic generation IDs. If you use strategy search by ID you should
change it to XPATH. One another problem is working with AJAX. Selenium supports AJAX executing but tester should predict
how many times the ajax call takes. You can use explicit or implicit wait for solve with problem.
Can Selenium be integrated to CI?
37 / 65
Yes. It can, because all tests can be exported to programming languages and then it can be run independent from Selenium IDE
by JUnit, TestNG and similar libraries
Can you use Selenium in commercial product?
Yes, you can. Selenium is distributed by Apache 2.0 license. It means that you can use it in commercial products free without
paing any charge.
What kind of disadvantages does Selenium IDE have?
After you recorded the user activates Selenium IDE generates the case tests tables. This tests table does not support the loops,
functions, conditions statements, so you cannot use all programming languages constructions.
What is Selenium Remote Control?
It is the test tool for web apps. It uses injecting JavaScript to browser for testing.
What advantages does Selenium have for compare with another web testing tools?
First, it is to start to write the tests, because you can record the user activity directly, Another thing is Selenium supports many
programming languages : Java, C#, Python, Ruby.
Can you install the Selenium IDE to another browsers then FireFox?
No. Selenium IDE can be installed only to FireFox.
What kind of browsers can be executed the tests by Selenium?
Firefox 3.x
IE 6-8
Safari 2-4
Opera 8-10
Chrome
Can you use Selenium for testing mobiles app?
Yes. if it can be run in mobiles browsers.
What is Selenese?
After you recorded the user activities, Selenium IDE generates the code, this code is written by Selenese.
How can you run the tests in HTTPS?
You need to use Selenium Server and configure the necessary securities environments.
How can you configure the Selenium Grid?
You can do in two ways: 1. adding special key when run the server, 2. using JSON config file.
What is HtmlUnitDriver?
HtmlUnitDriver is web driver which is used HtmlUnit engine. It is the faster web driver in Selenium.
Can you use navigations browser menu in Selenium tests?
Yes. you can. You can handle it with the following code:
driver.navigate().back(); driver.navigate().forward(); driver.navigate().refresh(); dri
ver.navigate().to();
How can you save the tests result?
You can take the screen shot if tests fail or you can store the testing result to database by JDBC.
Can you run the load tests by Selenium?
Yes, but Selenium is not good choose for such kind of tests. Because it is expense to open the multiple browser at the same time.
if you need to test loading, you can use JMeter or Gattling.
4.3
38 / 65
Conclusion
In this acticle we explained most of frequently ask questions in interviews and gived the answers. Of course this is not all. if you
want to improve your knowledge about Selemiun go to official web site Selenium Official Documentation.
39 / 65
Chapter 5
Introduction
With this example we are going to demonstrate how to use and configure Selenium standalone servers (Selenium Grid). We are
going to run the hub server and the two nodes. Each nodes will run the tests in different browsers.
Selenium Grid are the servers which compounds in distributed nodes. It offers you to run your selenium test on separate machines
in different kinds environments. This is great opportunities, because your tests can run parallels and use different browsers for
testing.
5.2
Below is shown high level architecture. It has the follow flow process. First we pass the tests to hub which send this tests to
specific nodes where all tests will be executed.
40 / 65
5.3
Configuration
Before we can start to configure the Selenium Grid we should download the necessary library. Selenium Grid consists only from
one JAR file. Go to the official site link and download the Selenium Server JAR file - selenium-server-standalone2.48.2.jar. This jar has the good help information. We should run this jar with the key -h that to print help information on
screen.
java -jar selenium-server-standalone-2.48.2.jar -h
This help information has all explanation about supported keys. This keys are used for configuration the instance server. First of
all we should run this jar with key -role hub. It means the this instance will be the hub server. It will be taken all receiving
tests and distributed to the specific nodes server. The hub server is run on 4444 port by default.
C:\Tools>java -jar selenium-server-standalone-2.48.2.jar -role hub
10:29:14.270 INFO - Launching Selenium Grid hub
2015-11-19 10:29:15.458:INFO::main: Logging initialized @1362ms
10:29:15.479 INFO - Will listen on 4444
10:29:15.563 INFO - Will listen on 4444
2015-11-19 10:29:15.568:INFO:osjs.Server:main: jetty-9.2.z-SNAPSHOT
2015-11-19 10:29:15.631:INFO:osjsh.ContextHandler:main: Started o.s.j.s.ServletC
ontextHandler@13f88ab{/,null,AVAILABLE}
2015-11-19 10:29:15.770:INFO:osjs.ServerConnector:main: Started ServerConnector@
646db9{HTTP/1.1}{0.0.0.0:4444}
41 / 65
The secondary step is to run the node instance. It can be done with key -role node as shown below. The same time we should
point where is located our hub server by key -hub https://localhost:4444/grid/register
C:\Tools>java -jar selenium-server-standalone-2.48.2.jar -role node -hub http:/
/localhost:4444/grid/register
10:31:08.635 INFO - Launching a Selenium Grid node
10:31:09.999 INFO - Java: Oracle Corporation 25.45-b02
10:31:10.000 INFO - OS: Windows 7 6.1 x86
10:31:10.009 INFO - v2.48.0, with Core v2.48.0. Built from revision 41bccdd
10:31:10.089 INFO - Driver class not found: com.opera.core.systems.OperaDriver
10:31:10.090 INFO - Driver provider com.opera.core.systems.OperaDriver is not re
gistered
10:31:10.153 INFO - Selenium Grid node is up and ready to register to the hub
10:31:10.215 INFO - Starting auto registration thread. Will try to register ever
y 5000 ms.
10:31:10.216 INFO - Registering the node to the hub: https://localhost:4444/grid/
register
10:31:10.254 INFO - The node is registered to the hub and ready to use
How you can see above the configuration process can be done by adding the keys in command line. But Selenium Server supports
another variant of configuration by file configuration in JSON format.
Firstly we should create the file which has the name - firefox_node.json. It can have any appropriate name.
{
"capabilities":
[
{
"browserName": "*firefox",
"maxInstances": 1,
"seleniumProtocol": "WebDriver"
}
],
"configuration":
{
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"maxSession": 5,
"port": 6543,
"host": 127.0.0.1,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": 127.0.0.1
}
}
We pointed there that all tests should be run in firefox. Now we can run the new node instance with this configurations. We use
-nodeConfig that to point which config file to use.
C:\Tools>java -jar selenium-server-standalone-2.48.2.jar -role node -nodeConfig
firefox_node.json
11:36:22.804 INFO - Launching a Selenium Grid node
11:36:23.789 INFO - Java: Oracle Corporation 25.45-b02
11:36:23.789 INFO - OS: Windows 7 6.1 x86
11:36:23.798 INFO - v2.48.0, with Core v2.48.0. Built from revision 41bccdd
11:36:23.884 INFO - Driver class not found: com.opera.core.systems.OperaDriver
11:36:23.885 INFO - Driver provider com.opera.core.systems.OperaDriver is not re
gistered
11:36:23.973
11:36:24.028
y 5000 ms.
11:36:24.029
register
11:36:24.041
42 / 65
Sometimes you can need only one instance server. For this reason you should run the selenium server without keys. All tests will
be executed in this instance in this case.
Another good opportunities are configure special browsers. For example, below we set the chrome browser environment.
5.4
Run tests
43 / 65
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/ xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ru</groupId>
<artifactId>parsentev</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.48.2</version>
</dependency>
</dependencies>
</project>
com.thoughtworks.selenium.DefaultSelenium;
com.thoughtworks.selenium.Selenium;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Tests for selenium standalone server.
* @author parsentev
* @since 19.11.2015
*/
public class SeleniumStandaloneServerTest {
@Test
public void executeFirefoxDriver() throws MalformedURLException {
this.execute(DesiredCapabilities.firefox());
}
@Test
public void executeChrome() throws MalformedURLException {
this.execute(DesiredCapabilities.chrome());
}
private void execute(final DesiredCapabilities capability) throws
MalformedURLException {
44 / 65
We can see details information about tests process on the node logs or screens. You should see somethings similar:
12:14:25.891 INFO - Executing: [new session: Capabilities [{browserName=firefox,
version=, platform=ANY}]])
12:14:25.903 INFO - Creating a new session for Capabilities [{browserName=firefo
x, version=, platform=ANY}]
12:14:30.143 INFO - Done: [new session: Capabilities [{browserName=firefox, vers
ion=, platform=ANY}]]
12:14:30.196 INFO - Executing: [get: https://www.javacodegeeks.com/])
12:14:34.283 INFO - Done: [get: https://www.javacodegeeks.com/]
12:14:34.299 INFO - Executing: [find element: By.name: s])
12:14:34.671 INFO - Done: [find element: By.name: s]
12:14:34.689 INFO - Executing: [send keys: 0 [[FirefoxDriver: firefox on WINDOWS
(2ca50141-8460-4012-bec4-b291e4042f55)] -> name: s], [selenuim]])
12:14:34.774 INFO - Done: [send keys: 0 [[FirefoxDriver: firefox on WINDOWS (2ca
50141-8460-4012-bec4-b291e4042f55)] -> name: s], [selenuim]]
12:14:34.784 INFO - Executing: [submit: 0 [[FirefoxDriver: firefox on WINDOWS (2
ca50141-8460-4012-bec4-b291e4042f55)] -> name: s]])
12:14:39.270 INFO - Done: [submit: 0 [[FirefoxDriver: firefox on WINDOWS (2ca501
41-8460-4012-bec4-b291e4042f55)] -> name: s]]
12:14:39.281 INFO - Executing: [get title])
12:14:39.311 INFO - Done: [get title]
12:14:39.327 INFO - Executing: [delete session: a459baef-2980-4fcc-8093-4ff4eecb
f03f])
12:14:39.806 INFO - Done: [delete session: a459baef-2980-4fcc-8093-4ff4eecbf03f]
When the test is received by node it looks appropriate browser in local machine. Then the node opens this browser and starts to
do the tests.
It can look like below:
45 / 65
46 / 65
5.5
Download
You can download the full source code of this example here: Selenium
47 / 65
Chapter 6
Introduction
In this article, we are going to show how you can write automation tests by Selenium and JUnit.
Selenium is tools for building automation tests. Selenium can be used only for testing web applications. When Selenium executes
the test, it injects the JavaScript codes to browser or it uses the native browser API. It does not mean that you should write all
codes only on JavaScript. Selenium supports all most popular programming languages : Java, C#, Python, Ruby and so.
JUnit is a unit testing framework for the Java programming language. In this example, we will integrate Selenium to this
framework. Actually, Selenium IDE has all functionality to write, build and execute automation tests, but if you want to execute
tests independently from Selenium IDE you need to use JUnit or another libraries for automation tests.
6.2
The simplest way to get the base test cases code is to record user activities in Selenium IDE. Firstly, you should install Selenium
IDE. Actually, Selenium IDE is the Firefox add-ons. After you install this plugin, you can see the Selenium IDE button in the
right top corner in Firefox. This plugin is supported only by Firefox.
48 / 65
49 / 65
50 / 65
51 / 65
6.3
Integrate to JUnit
The next step is to create the new maven project with JUnit and Selenium dependencies. We will create this new project from
default archetype by this follows command
mvn -B archetype:generate -DarchetypeGroupId=org.apache.maven.archetypes -DgroupId=ru. parsentev.app -DartifactId=EbayAdvancedSearch
52 / 65
53 / 65
54 / 65
You can find the full source code of this case below.
EbayAdvancedSearch.java
package ru.parsentev.app;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.By;
import
import
import
import
import
import
import
import
import
55 / 65
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.WebDriver;
com.thoughtworks.selenium.webdriven.WebDriverBackedSelenium;
org.junit.After;
org.junit.Before;
org.junit.Test;
static org.junit.Assert.*;
java.util.regex.Pattern;
static org.apache.commons.lang3.StringUtils.join;
Now, we can run this project by this follows command mvn test
56 / 65
6.4
Conclusion
In this article, we have shown how you can integrate Selenium and JUnit frameworks. If you want to get more information about
this framework, please vitis official web sites: Selenium and JUnit.
6.5
Download
You can download the full source code of this example here: Selenium JUnit
57 / 65
58 / 65
Chapter 7
Introduction
In this tutorial, we are going to explain what Selenium Grid is and how you can use it in your project. We are going to install and
configure the Selenium Grid, write and execute the tests on it. Selenium Grid is one of tool from Selenium framework. It is the
distributed system for execution tests.
It has few benefits:
You can execute tests in parallel, so it can reduce the execution time.
You can set particular environments for tests.
Actually. It is the daunting task to reduce the tests executions time, because some of functional tests spent about hour for
executions process. Selenium team offers the great solutions for it. It uses the separate nodes, which compound in full distributed
system. For this reason, it can be scaled easily.
Below you can see the highly level architecture.
59 / 65
7.2
Firstly, you should download the necessary library. The great thing about Selenium Grid is that you need only one JAR file. You
need to go to the official web site seleniumhq.org/download and download the Selenium Server. It can be configured to
Selenium Grid.
Below you can see the download page:
60 / 65
7.3
Usage cases
How we said before, all you need is the Selenium Server JAR. You can run it this key --help, that get help information about
supported operations.
c:\Users\parsentev\Downloads>java -jar selenium-server-standalone-2.49.1.jar -help
Running as a standalone server:
Usage: java -jar selenium-server.jar [-interactive] [options]
-port : the port number the selenium server should use
(default 4444)
-timeout : an integer number of seconds we should allow a
client to be idle
-browserTimeout : an integer number of seconds a browser is
allowed to hang
-interactive: puts you into interactive mode. See the tutorial for
more details
-singleWindow: puts you into a mode where the test web site
executes in a frame. This mode should only be selected if the
application under test does not use frames.
-profilesLocation: Specifies the directory that holds the profiles
that java clients can use to start up selenium. Currently
supported for Firefox only.
-forcedBrowserMode : sets the browser mode to a single
argument (e.g. "*iexplore") for all sessions, no matter what is
passed to getNewBrowserSession
-forcedBrowserModeRestOfLine : sets the browser mode to
61 / 65
How you can see in the architecture diagram, firstly, we need to run the HUB nodes. It will takes all receiving tests and route to
participated nodes, which has appropriate environment.
You need to run the JAR with follow key -role hub
62 / 65
63 / 65
How you can see, we need to add the Selenium library in dependencies. Then, lets create the simple test cases, when we want
to test the search function in https://www.javacodegeeks.com/
ruparsentevSeleniumStantaloneServerTest.java
package ru.parsentev;
import
import
import
import
import
import
import
import
com.thoughtworks.selenium.DefaultSelenium;
com.thoughtworks.selenium.Selenium;
org.junit.Test;
org.openqa.selenium.By;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.remote.DesiredCapabilities;
org.openqa.selenium.remote.RemoteWebDriver;
import java.net.MalformedURLException;
import java.net.URL;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Tests for selenium standalone server.
* @author parsentev
* @since 19.11.2015
*/
public class SeleniumStandaloneServerTest {
@Test
public void executeFirefoxDriver() throws MalformedURLException {
this.execute(DesiredCapabilities.firefox());
}
@Test
public void executeChrome() throws MalformedURLException {
this.execute(DesiredCapabilities.chrome());
64 / 65
}
private void execute(final DesiredCapabilities capability) throws MalformedURLException {
WebDriver driver = new RemoteWebDriver(
new URL("https://localhost:4444/wd/hub"), capability
);
driver.get("https://www.javacodegeeks.com/");
WebElement element = driver.findElement(By.name("s"));
element.sendKeys("selenuim");
element.submit();
assertThat(
driver.getTitle(),
is("You searched for selenuim | Java Code Geeks")
);
driver.quit();
}
}
In example above, we pointed that we want to execute the test on Chrome and Firefox browsers by following commands:
DesiredCapabilities.chrome().
You can set more specific requirments for execution environments by additional API, which offer the Selenium library:
capability.setBrowserName();
capability.setPlatform();
capability.setVersion()
capability.setCapability(,);
The same time, you need to configure your nodes for particular environment. Selenium Grid supports two way, how you can do
it.
It is used command-line key. For example, we want that this node execute only tests in Internet Explorer 9. We can configure
in like: -browser browserName=iexplorer,version=9,platform=WINDOWS
It is used JSON configuration file.
{
"capabilities":
[
{
"browserName": "*firefox",
"maxInstances": 1,
"seleniumProtocol": "WebDriver"
}
],
"configuration":
{
"proxy": "org.openqa.grid.selenium.proxy.DefaultRemoteProxy",
"maxSession": 5,
"port": 6543,
"host": 127.0.0.1,
"register": true,
"registerCycle": 5000,
"hubPort": 4444,
"hubHost": 127.0.0.1
}
}
7.4
65 / 65
Conclusion
In this article, we explained what Selenium Grid is and shown how to configure, run, execute tests. We could not cover all narrow
things about Selenium Grid, so if you want to improve your knowledge about Selenium and particular about Selenium Grid,
please, visit the official web site seleniumhq.org
7.5
Download
You can download the full source code of this example here: SeleniumGrid