Selenium 简明教程
Selenium - Overview
Introduction
Selenium 是一种开源且可移植的自动软件测试工具,用于测试 Web 应用程序。它具有在不同浏览器和操作系统中操作的能力。Selenium 不仅仅是一个工具,而是一组工具,可帮助测试人员更有效地自动化基于 Web 的应用程序。
Selenium is an open-source and a portable automated software testing tool for testing web applications. It has capabilities to operate across different browsers and operating systems. Selenium is not just a single tool but a set of tools that helps testers to automate web-based applications more efficiently.
现在,让我们了解 Selenium 套件中提供的每个工具及其用法。
Let us now understand each one of the tools available in the Selenium suite and their usage.
Sr.No. |
Tool & Description |
1 |
Selenium IDE Selenium *I*ntegrated *D*evelopment *E*nvironment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test. |
2 |
Selenium RC Selenium *R*emote *C*ontrol (RC) was the flagship testing framework that allowed more than simple browser actions and linear execution. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests. |
3 |
Selenium WebDriver Selenium WebDriver is the successor to Selenium RC which sends commands directly to the browser and retrieves results. |
4 |
Selenium Grid Selenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time. |
Advantages of Selenium
QTP 和 Selenium 是市场上使用最广泛的软件自动化测试工具。因此,有必要比较 Selenium 相对于 QTP 的优点。
QTP and Selenium are the most used tools in the market for software automation testing. Hence it makes sense to compare the pros of Selenium over QTP.
Selenium |
QTP |
Selenium is an open-source tool. |
QTP is a commercial tool and there is a cost involved in each one of the licenses. |
Can be extended for various technologies that expose DOM. |
Limited add-ons and needs add-ons for each one of the technologies. |
Has capabilities to execute scripts across different browsers. |
Can run tests in specific versions of Firefox , IE, and Chrome. |
Can execute scripts on various operating systems. |
Works only with Windows. |
Supports mobile devices. |
Supports mobile devices with the help of third-party tools. |
Executes tests within the browser, so focus is NOT required while script execution is in progress. |
Needs Focus during script execution, as the tool acts on the browser (mimics user actions). |
Can execute tests in parallel with the use of Selenium Grids. |
QTP cannot execute tests in parallel, however integrating QTP with QC allows testers to execute in parallel. QC is also a commercial tool. |
Disadvantages of Selenium
现在让我们来讨论 Selenium 优于 QTP 的缺点。
Let us now discuss the pitfalls of Selenium over QTP.
Selenium |
QTP |
Supports only web based applications. |
Can test both web and desktop applications. |
No feature such as Object Repository/Recovery Scenario |
QTP has built-in object repositories and recovery scenarios. |
No IDE, so the script development won’t be as fast as QTP. |
More intuitive IDE; automation can be achieved faster. |
Cannot access controls within the browser. |
Can access controls within the browser such as favorites bar, backward, and forward buttons. |
No default test report generation. |
Default test result generation within the tool. |
For parameterization, users has to rely on the programming language. |
Parameterization is built-in and easy to implement. |
Selenium - IDE
Selenium-IDE(集成开发环境)是一个易于使用的 Firefox 插件,用于开发 Selenium 测试用例。它提供了一个图形用户界面,用于记录使用 Firefox 的用户操作,用于学习和使用 Selenium,但它只能与 Firefox 浏览器一起使用,因为不支持其他浏览器。
The Selenium-IDE (Integrated Development Environment) is an easy-to-use Firefox plug-in to develop Selenium test cases. It provides a Graphical User Interface for recording user actions using Firefox which is used to learn and use Selenium, but it can only be used with Firefox browser as other browsers are not supported.
但是,记录的脚本可以转换为 Selenium 支持的各种编程语言,并且脚本也可以在其他浏览器上执行。
However, the recorded scripts can be converted into various programming languages supported by Selenium and the scripts can be executed on other browsers as well.
下表列出了我们将在本章中涵盖的部分内容。
The following table lists the sections that we are going to cover in this chapter.
Sr.No. |
Title & Description |
1 |
Download Selenium IDEThis section deals with how to download and configure Selenium IDE. |
2 |
Selenium IDE FeaturesThis section deals with the features available in Selenium IDE. |
3 |
Creating Selenium IDE TestsThis section deals with how to create IDE tests using recording feature. |
4 |
Selenium IDE Script DebuggingThis section deals with debugging the Selenium IDE script. |
5 |
Inserting Verification PointsThis section describes how to insert verification points in Selenium IDE. |
6 |
Selenium Pattern MatchingThis section deals with how to work with regular expressions using IDE. |
7 |
Selenium User ExtensionsThe Java script that allows users to customize or add new functionality. |
8 |
Different Browser ExecutionThis section deals with how to execute Selenium IDE scripts on different browsers. |
Selenium - Environment Setup
为了开发 Selenium RC 或 WebDriver 脚本,用户必须确保已完成初始配置。设置环境涉及以下步骤。
In order to develop Selenium RC or WebDriver scripts, users have to ensure that they have the initial configuration done. Setting up the environment involves the following steps.
-
Download and Install Java
-
Download and Configure Eclipse
-
Configure FireBug and FirePath
-
Configure Selenium RC
-
Configure Selenium WebDriver
Download and Install Java
为了使用 Selenium WebDriver/Selenium,我们需要安装 JDK(Java 开发工具包)。让我们看看如何下载和安装 Java。
We need to have JDK (Java Development Kit) installed in order to work with Selenium WebDriver/Selenium. Let us see how to download and install Java.
Step 1 − 导航至 UR。
Step 1 − Navigate to the UR.
Step 2 − 转到“下载”区域,并选择“JDK 下载”。
Step 2 − Go to "Downloads" section and select "JDK Download".
Step 3 − 选中“接受许可协议”单选按钮。
Step 3 − Select "Accept License Agreement" radio button.
Step 4 − 选择适当的安装。在本例中,是“Windows 7-64”位。单击适当的链接,并将 .exe 文件保存至磁盘。
Step 4 − Select the appropriate installation. In this case, it is 'Windows 7-64' bit. Click the appropriate link and save the .exe file to your disk.
Step 5 − 运行下载的 exe 文件,以启动安装程序向导。单击“下一步”继续。
Step 5 − Run the downloaded exe file to launch the Installer wizard. Click 'Next' to continue.
Step 6 − 选择功能,然后单击“下一步”。
Step 6 − Select the features and click 'Next'.
Step 7 − 提取安装程序,并显示其在向导中的进度。
Step 7 − The installer is extracted and its progress is shown in the wizard.
Step 8 − 用户可以选择安装位置,然后单击“下一步”。
Step 8 − The user can choose the install location and click 'Next'.
Step 9 − 安装程序安装 JDK 并复制新文件。
Step 9 − The installer installs the JDK and new files are copied across.
Step 10 − 安装程序安装成功并向用户显示。
Step 10 − The Installer installs successfully and displays the same to the user.
Step 11 − 要验证安装是否成功,请转到命令提示符并只键入“java”作为命令。该命令的输出示于下文。如果 Java 安装不成功或尚未安装,则会引发“命令未知”错误。
Step 11 − To verify if the installation was successful, go to the command prompt and just type 'java' as a command. The output of the command is shown below. If the Java installation is unsuccessful or if it had NOT been installed, it would throw an "unknown command" error.
Download and Configure Eclipse
Step 1 − 访问 URL: https://www.eclipse.org/downloads/ 并根据 OS 架构下载适当的文件。
Step 1 − Navigate to the URL: https://www.eclipse.org/downloads/ and download the appropriate file based on your OS architecture.
Step 2 − 单击“下载”按钮。
Step 2 − Click the 'Download' button.
Step 3 − 该下载将为压缩格式。解压缩内容。
Step 3 − The download would be in a Zipped format. Unzip the contents.
Step 4 − 找到 Eclipse.exe 并双击该文件。
Step 4 − Locate Eclipse.exe and double click on the file.
Step 5 − 要配置工作区,请选择开发必须发生的位置。
Step 5 − To configure the workspace, select the location where the development has to take place.
Step 6 − Eclipse 窗口打开,如下所示。
Step 6 − The Eclipse window opens as shown below.
Configure FireBug and FirePath
要使用 Selenium RC 或 WebDriver,我们需要根据 XPath 或 ID 或名称等找到元素。为了找到元素,我们需要工具/插件。
To work with Selenium RC or WebDriver, we need to locate elements based on their XPath or ID or name, etc. In order to locate an element, we need tools/plugins.
Step 1 − 访问 URL: https://addons.mozilla.org/en-US/firefox/addon/firebug/ 并下载插件。
Step 1 − Navigate to the URL : https://addons.mozilla.org/en-US/firefox/addon/firebug/ and download plugin.
Step 2 − 会向用户显示插件安装程序,并且在单击“安装”按钮后立即安装它。
Step 2 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Step 3 − 安装后,我们可以通过转到“Web 开发人员”>>“Firebug”来启动该插件。
Step 3 − After installing, we can launch the plugin by navigating to "Web Developer" >> "Firebug".
Step 4 − FirePath 是在 Firebug 中工作的插件,它可以帮助用户获取元素的“XPath”。通过导航到“ https://addons.mozilla.org/en-US/firefox/addon/firepath/ " 安装 FirePath。
Step 4 − FirePath, a plugin that works within Firebug, helps users to grab the 'XPath' of an element. Install FirePath by navigating to "https://addons.mozilla.org/en-US/firefox/addon/firepath/"
Step 5 − 会向用户显示插件安装程序,并且在单击“安装”按钮后立即安装它。
Step 5 − The add-on installer is shown to the user and it is installed upon clicking the 'Install' button.
Step 6 − 现在通过导航到“工具”>>“Web 开发人员”>>“Firebug”来启动“Firebug”。
Step 6 − Now launch "Firebug" by navigating to "Tools" >> "Webdeveloper" >> "Firebug".
Example
现在让我们了解通过一个示例如何在 Firebug 和 FirePath 中使用它。为演示,我们将使用 www.google.com 并捕获“google.com”文本框的属性。
Now let us understand how to use FireBug and FirePath with an example. For demonstration, we will use www.google.com and capture the properties of the text box of "google.com".
Step 1 − 首先单击以下屏幕截图中突出显示的箭头图标,并将其拖动到我们要捕获其属性的对象。该对象的 HTML/DOM 将显示如下。我们能够捕获可以与之交互的输入文本框的“ID”。
Step 1 − First click on the arrow icon as highlighted in the following screenshot and drag it to the object for which we would like to capture the properties. The HTML/DOM of the object would be displayed as shown below. We are able to capture the 'ID' of the input text box with which we can interact.
Step 2 − 要获取对象的 XPath,请转到“firepath”选项卡并执行以下步骤。
Step 2 − To fetch the XPath of the object, go to 'firepath' tab and perform the following steps.
-
Click the Spy icon.
-
Select the Control for which we would like to capture the XPath.
-
XPath of the selected control would be generated.
Configure Selenium RC
现在让我们看看如何配置 Selenium Remote 控制。我们会在后面的章节了解如何用 Selenium RC 开发脚本,但是现在我们只了解它的配置部分。
Now let us look at how to configure Selenium Remote control. We will understand how to develop scripts with Selenium RC in later chapters, however for now, we will understand just the configuration part of it.
Step 1 − 导航到 Selenium 下载部分 http://www.seleniumhq.org/download/ ,并单击其版本号下载 Selenium Server,如下所示。
Step 1 − Navigate to the Selenium downloads section http://www.seleniumhq.org/download/ and download Selenium Server by clicking on its version number as shown below.
Step 2 − 下载后,我们需要启动 Selenium Server。为此,打开命令提示符并导航到保存下载的 JAR 文件的文件夹,如下所示。
Step 2 − After downloading, we need to start the Selenium Server. To do so, open command prompt and navigate to the folder where the downloaded JAR file is kept as shown below.
Step 3 − 要启动服务器,请使用命令 'java -jar [downloaded jar name ] 如果 java JDK 已正确安装,你将收到一条成功的消息,如下所示。现在我们可以开始编写 Selenium RC 脚本。
Step 3 − To start the server, use the command 'java -jar [downloaded jar name ] and if java JDK is installed properly, you would get a success message as shown below. Now we can start writing Selenium RC scripts.
Configure Selenium WebDriver
现在让我们来看看如何配置 Selenium WebDriver。我们会在后面的章节了解如何用 Selenium WebDriver 开发脚本,但是现在我们只了解它的配置部分。
Now let us look at how to configure Selenium WebDriver. We will understand how to develop scripts with Selenium WebDriver in later chapters, however for now, we will understand just the configuration part of it.
Step 1 − 导航到 selenium 下载部分 http://www.seleniumhq.org/download/ ,并单击其版本号下载 Selenium WebDriver,如下所示。
Step 1 − Navigate to the selenium downloads section http://www.seleniumhq.org/download/ and download Selenium WebDriver by clicking on its version number as shown below.
Step 2 − 下载的文件为 Zip 格式,必须解压内容才能将其映射到项目文件夹。
Step 2 − The downloaded file is in Zipped format and one has to unzip the contents to map it to the project folder.
Step 3 − 解压的内容将按如下所示显示。如何将其映射到项目文件夹和如何开始编写脚本将在 WebDriver 章节中进行讨论。
Step 3 − The Unzipped contents would be displayed as shown below. How to map it to the project folder and how to start scripting would be dealt in the webDriver chapter.
Selenium - Remote Control
What is Selenium RC?
Selenium Remote Control (RC) 是一个主要的 Selenium 项目,它在 Selenium WebDriver(Selenium 2.0) 出现之前持续了很长时间。现在 Selenium RC 几乎不再使用,因为 WebDriver 提供了更多强大的功能,但用户仍可以使用 RC 继续开发脚本。
Selenium Remote Control (RC) was the main Selenium project that sustained for a long time before Selenium WebDriver(Selenium 2.0) came into existence. Now Selenium RC is hardly in use, as WebDriver offers more powerful features, however users can still continue to develop scripts using RC.
它允许我们借助编程语言(如 Java、C#、Perl、Python 和 PHP)的全部功能编写自动 Web 应用程序 UI 测试,以创建更复杂的测试,比如读取和写入文件、查询数据库和发送电子邮件测试结果。
It allows us to write automated web application UI tests with the help of full power of programming languages such as Java, C#, Perl, Python and PHP to create more complex tests such as reading and writing files, querying a database, and emailing test results.
Selenium RC Architecture
Selenium RC 的工作方式是客户端库可以通过传递每个要执行的 Selenium 命令与 Selenium RC Server 通信。然后,服务器使用 Selenium-Core JavaScript 命令将 Selenium 命令传递给浏览器。
Selenium RC works in such a way that the client libraries can communicate with the Selenium RC Server passing each Selenium command for execution. Then the server passes the Selenium command to the browser using Selenium-Core JavaScript commands.
浏览器使用其 JavaScript 解释器执行 Selenium 命令。
The browser executes the Selenium command using its JavaScript interpreter.
Selenium RC 分为两部分。
Selenium RC comes in two parts.
-
The Selenium Server launches and kills browsers. In addition to that, it interprets and executes the Selenese commands. It also acts as an HTTP proxy by intercepting and verifying HTTP messages passed between the browser and the application under test.
-
Client libraries that provide an interface between each one of the programming languages (Java, C#, Perl, Python and PHP) and the Selenium-RC Server.
RC Scripting
现在,让我们使用 Selenium Remote Control 编写一个示例脚本。我们使用 http://www.calculator.net/ 来了解 Selenium RC。我们将使用“Math Calculators”模块下的“Percent Calculator”执行百分比计算。
Now let us write a sample script using Selenium Remote Control. Let us use http://www.calculator.net/ for understanding Selenium RC. We will perform a Percent calculation using 'Percent Calculator' that is present under the 'Math Calculators' module.
Step 1 − 启动 Selenium Remote Control(借助命令提示符)。
Step 1 − Start Selenium Remote Control (with the help of command prompt).
Step 2 − 启动 Selenium RC 后,打开 Eclipse 并创建一个“New Project”,如下所示。
Step 2 − After launching Selenium RC, open Eclipse and create a "New Project" as shown below.
Step 3 − 输入项目名并单击“下一步”按钮。
Step 3 − Enter the project name and click 'Next' button.
Step 4 − 检查源、项目、数据库,以及输出文件夹,并单击“完成”。
Step 4 − Verify the Source, Projects, Libraries, and Output folder and click 'Finish'.
Step 5 − 右键单击“项目”容器,并选择“配置构建路径”。
Step 5 − Right click on 'project' container and choose 'Configure Build Path'.
Step 6 − 为“selrcdemo”打开属性。导航到“数据库”选项卡,并选择“添加外部 JAR”。选择我们已经下载的 Selenium RC jar 文件,它将如下所示显示。
Step 6 − Properties for 'selrcdemo' opens up. Navigate to 'Libraries' tab and select 'Add External JARs'. Choose the Selenium RC jar file that we have downloaded and it would appear as shown below.
Step 7 − 引用数据库如下所示显示。
Step 7 − The referenced Libraries are shown as displayed below.
Step 8 − 通过右键单击“源”文件夹并选择“新建”>>“类”,来创建一个新类文件。
Step 8 − Create a new class file by performing a right click on 'src' folder and select 'New' >> 'class'.
Step 9 − 输入一个类文件名并启用“public static void main”如下所示。
Step 9 − Enter a name of the class file and enable 'public static void main' as shown below.
Step 10 − 创建的类在文件夹结构下创建,如下所示。
Step 10 − The Created Class is created under the folder structure as shown below.
Step 11 − 现在是编码时间。以下代码嵌入了解释,以使读者了解所介绍的内容。
Step 11 − Now it is time for coding. The following code has comments embedded in it to make the readers understand what has been put forth.
package selrcdemo;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
public class rcdemo {
public static void main(String[] args) throws InterruptedException {
// Instatiate the RC Server
Selenium selenium = new DefaultSelenium("localhost", 4444 , "firefox", "http://www.calculator.net");
selenium.start(); // Start
selenium.open("/"); // Open the URL
selenium.windowMaximize();
// Click on Link Math Calculator
selenium.click("xpath = .//*[@id = 'menu']/div[3]/a");
Thread.sleep(2500); // Wait for page load
// Click on Link Percent Calculator
selenium.click("xpath = .//*[@id = 'menu']/div[4]/div[3]/a");
Thread.sleep(4000); // Wait for page load
// Focus on text Box
selenium.focus("name = cpar1");
// enter a value in Text box 1
selenium.type("css=input[name = \"cpar1\"]", "10");
// enter a value in Text box 2
selenium.focus("name = cpar2");
selenium.type("css = input[name = \"cpar2\"]", "50");
// Click Calculate button
selenium.click("xpath = .//*[@id = 'content']/table/tbody/tr/td[2]/input");
// verify if the result is 5
String result = selenium.getText(".//*[@id = 'content']/p[2]");
if (result == "5") {
System.out.println("Pass");
} else {
System.out.println("Fail");
}
}
}
Step 12 − 现在,让我们通过单击“运行”按钮来执行脚本来。
Step 12 − Now, let us execute the script by clicking 'Run' Button.
Step 13 − 脚本将开始执行,用户将能够在“命令历史”选项卡下看到命令历史。
Step 13 − The script would start executing and user would be able to see the command history under 'Command History' Tab.
Step 14 − 应用程序的最后状态如下图所示。计算百分比并将其显示在屏幕上,如下所示。
Step 14 − The final state of the application is shown as below. The percentage is calculated and it displayed the result on screen as shown below.
Step 15 − 测试的输出打印在 Eclipse 控制台上,如下所示,因为我们将输出打印到控制台。在实时中,输出将写入 HTML 文件或简单的文本文件。
Step 15 − The output of the test is printed on the Eclipse console as shown below as we have printed the output to the console. In real time the output is written to an HTML file or in a simple Text file.
Selenium - Selenese Commands
命令是指 Selenium 所要执行的操作,Selenium 中的命令分为三种类型。点击其中的每一项以了解有关命令的更多信息。
A command refers to what Selenium has to do and commands in selenium are of three types. Click on each one of them to know more about the commands.
Locators
元素定位器帮助 Selenium 识别命令引用的 HTML 元素。所有这些定位器都可以在 Mozilla 的 FirePath 和 FireBug 插件的帮助下识别。有关详细信息,请参阅环境设置章节。
Element Locators help Selenium to identify the HTML element the command refers to. All these locators can be identified with the help of FirePath and FireBug plugin of Mozilla. Please refer the Environment Setup chapter for details.
-
identifier = id Select the element with the specified "id" attribute and if there is no match, select the first element whose @name attribute is id.
-
id = id Select the element with the specified "id" attribute.
-
name = name Select the first element with the specified "name" attribute
-
dom = javascriptExpression Selenium finds an element by evaluating the specified string that allows us to traverse through the HTML Document Object Model using JavaScript. Users cannot return a value but can evaluate as an expression in the block.
-
xpath = xpathExpression Locate an element using an XPath expression.
-
link = textPattern Select the link element (within anchor tags) which contains text matching the specified pattern.
-
css = cssSelectorSyntax Select the element using css selector.
Selenium - Webdriver
WebDriver 是一个用于自动测试 Web 应用程序的工具。它通常被称为 Selenium 2.0。WebDriver 使用了不同的底层框架,而 Selenium RC 则使用嵌入在浏览器中且存在一些限制的 JavaScript Selenium-Core。与依赖于服务器的 Selenium RC 不同,WebDriver 直接与浏览器进行交互,没有任何中间方。它用于以下情况:
WebDriver is a tool for automating testing web applications. It is popularly known as Selenium 2.0. WebDriver uses a different underlying framework, while Selenium RC uses JavaScript Selenium-Core embedded within the browser which has got some limitations. WebDriver interacts directly with the browser without any intermediary, unlike Selenium RC that depends on a server. It is used in the following context −
-
Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0).
-
Handling multiple frames, multiple browser windows, popups, and alerts.
-
Complex page navigation.
-
Advanced user navigation such as drag-and-drop.
-
AJAX-based UI elements.
Architecture
可以使用下面所示的简单架构图最恰当地解释 WebDriver。
WebDriver is best explained with a simple architecture diagram as shown below.
Selenium RC Vs WebDriver
Selenium RC |
Selenium WebDriver |
The architecture of Selenium RC is complicated, as the server needs to be up and running before starting a test. |
WebDriver’s architecture is simpler than Selenium RC, as it controls the browser from the OS level. |
Selenium server acts as a middleman between the browser and Selenese commands. |
WebDriver interacts directly with the browser and uses the browser’s engine to control it. |
Selenium RC script execution is slower, since it uses a Javascript to interact with RC. |
WebDriver is faster, as it interacts directly with the browser. |
Selenium RC cannot support headless execution as it needs a real browser to work with. |
WebDriver can support the headless execution. |
It’s a simple and small API. |
Complex and a bit large API as compared to RC. |
Less object-oriented API. |
Purely object oriented API. |
Cannot test mobile Applications. |
Can test iPhone/Android applications. |
Scripting using WebDriver
让我们了解如何使用 WebDriver。为了演示,我们将使用 https://www.calculator.net/ 。我们将在“Math Calculator”下执行一个名为“Percent Calculator”的计算。我们已经下载了所需的 WebDriver JAR。有关详细信息,请参阅“环境设置”一章。
Let us understand how to work with WebDriver. For demonstration, we would use https://www.calculator.net/. We will perform a "Percent Calculator" which is located under "Math Calculator". We have already downloaded the required WebDriver JAR’s. Refer the chapter "Environmental Setup" for details.
Step 1 - 从解压的 Eclipse 文件夹中启动“Eclipse”。
Step 1 − Launch "Eclipse" from the Extracted Eclipse folder.
Step 2 - 单击“浏览”按钮,选择工作空间。
Step 2 − Select the Workspace by clicking the 'Browse' button.
Step 3 - 现在从“文件”菜单创建“新项目”。
Step 3 − Now create a 'New Project' from 'File' menu.
Step 4 - 输入项目名称,然后单击“下一步”。
Step 4 − Enter the Project Name and Click 'Next'.
Step 5 - 转到“库”选项卡,选择我们下载的所有 JAR 文件。添加对 Selenium WebDriver 库文件夹中所有 JAR 文件以及 selenium-java-2.42.2.jar 和 selenium-java-2.42.2-srcs.jar 的引用。
Step 5 − Go to Libraries Tab and select all the JAR’s that we have downloaded. Add reference to all the JAR’s of Selenium WebDriver Library folder and also selenium-java-2.42.2.jar and selenium-java-2.42.2-srcs.jar.
Step 6 - 如下所示创建包。
Step 6 − The Package is created as shown below.
Step 7 - 现在右键单击包,然后选择“新建”>>“类”以创建一个“类”。
Step 7 − Now right-click on the package and select 'New' >> 'Class' to create a 'class'.
Step 8 - 现在对类命名并使其成为主函数。
Step 8 − Now name the class and make it the main function.
Step 9 - 如下所示,显示类大纲。
Step 9 − The class outline is shown as below.
Step 10 - 现在是时候编写代码了。以下脚本更容易理解,因为它包含嵌入式注释来清晰地解释步骤。请参阅“定位器”一章,了解如何获取对象属性。
Step 10 − Now it is time to code. The following script is easier to understand, as it has comments embedded in it to explain the steps clearly. Please take a look at the chapter "Locators" to understand how to capture object properties.
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class webdriverdemo {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
//Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch website
driver.navigate().to("http://www.calculator.net/");
//Maximize the browser
driver.manage().window().maximize();
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr[2]/td/input[2]")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
//Close the Browser.
driver.close();
}
}
Step 11 - 以上脚本的输出将打印在控制台中。
Step 11 − The output of the above script would be printed in Console.
Most Used Commands
下表列出了 WebDriver 中一些最常用的命令及其语法。
The following table lists some of the most frequently used commands in WebDriver along with their syntax.
Sr.No. |
Command & Description |
1 |
driver.get("URL") To navigate to an application. |
2 |
element.sendKeys("inputtext") Enter some text into an input box. |
3 |
element.clear() Clear the contents from the input box. |
4 |
select.deselectAll() Deselect all OPTIONs from the first SELECT on the page. |
5 |
select.selectByVisibleText("some text") Select the OPTION with the input specified by the user. |
6 |
driver.switchTo().window("windowName") Move the focus from one window to another. |
7 |
driver.switchTo().frame("frameName") Swing from frame to frame. |
8 |
driver.switchTo().alert() Helps in handling alerts. |
9 |
driver.navigate().to("URL") Navigate to the URL. |
10 |
driver.navigate().forward() To navigate forward. |
11 |
driver.navigate().back() To navigate back. |
12 |
driver.close() Closes the current browser associated with the driver. |
13 |
driver.quit() Quits the driver and closes all the associated window of that driver. |
14 |
driver.refresh() Refreshes the current page. |
Selenium - Locators
使用 WebDriver 和 WebElement 类提供的 findElement() 和 findElements() 方法可帮助在 Selenium WebDriver 中查找元素。
Locating elements in Selenium WebDriver is performed with the help of findElement() and findElements() methods provided by WebDriver and WebElement class.
-
findElement() returns a WebElement object based on a specified search criteria or ends up throwing an exception if it does not find any element matching the search criteria.
-
findElements() returns a list of WebElements matching the search criteria. If no elements are found, it returns an empty list.
下表列出了在 Selenium WebDriver 中查找元素的所有 Java 语法。
The following table lists all the Java syntax for locating elements in Selenium WebDriver.
Method |
Syntax |
Description |
By ID |
driver.findElement(By.id (<element ID>)) |
Locates an element using the ID attribute |
By name |
driver.findElement(By.name (<element name>)) |
Locates an element using the Name attribute |
By class name |
driver.findElement(By.className (<element class>)) |
Locates an element using the Class attribute |
By tag name |
driver.findElement(By.tagName (<htmltagname>)) |
Locates an element using the HTML tag |
By link text |
driver.findElement(By.linkText (<linktext>)) |
Locates a link using link text |
By partial link text |
driver.findElement(By.partialLinkText (<linktext>)) |
Locates a link using the link’s partial text |
By CSS |
driver.findElement(By.cssSelector (<css selector>)) |
Locates an element using the CSS selector |
By XPath |
driver.findElement(By.xpath (<xpath>)) |
Locates an element using XPath query |
Locators Usage
下面我们利用 https://www.calculator.net 了解每个定位器方法的实际用法
Now let us understand the practical usage of each of the locator methods with the help of https://www.calculator.net
By ID
此处通过 ID 访问对象。在本例中,是文本框的 ID。使用 sendkeys 方法利用 ID(cdensity) 将值输入文本框。
Here an object is accessed with the help of IDs. In this case, it is the ID of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity).
driver.findElement(By.id("cdensity")).sendKeys("10");
By Name
此处通过名称访问对象。在本例中,是文本框的名称。使用 sendkeys 方法利用 ID(cdensity) 将值输入文本框。
Here an object is accessed with the help of names. In this case, it is the name of the text box. Values are entered into the text box using the sendkeys method with the help of ID(cdensity).
driver.findElement(By.name("cdensity")).sendKeys("10");
By Class Name
此处通过类名访问对象。在本例中,是 WebElement 的类名。可以通过 gettext 方法访问该值。
Here an object is accessed with the help of Class Names. In this case, it is the Class name of the WebElement. The Value can be accessed with the help of the gettext method.
List<WebElement> byclass = driver.findElements(By.className("smalltext smtb"));
By Tag Name
元素的 DOM 标记名称可用于在 WebDriver 中查找该特定元素。使用此方法处理表非常容易。请参阅以下代码。
The DOM Tag Name of an element can be used to locate that particular element in the WebDriver. It is very easy to handle tables with the help of this method. Take a look at the following code.
WebElement table = driver.findElement(By.id("calctable"));
List<WebElement> row = table.findElements(By.tagName("tr"));
int rowcount = row.size();
By Link Text
此方法可帮助查找具有匹配可见文本的链接元素。
This method helps to locate a link element with matching visible text.
driver.findElements(By.linkText("Volume")).click();
By partial link text
此方法可帮助查找具有部分匹配可见文本的链接元素。
This methods helps locate a link element with partial matching visible text.
driver.findElement(By.partialLinkText("Volume")).click();
By CSS
CSS 用作识别 Web 对象的方法,但并非所有浏览器都支持 CSS 识别。
The CSS is used as a method to identify the webobject, however NOT all browsers support CSS identification.
WebElement loginButton = driver.findElement(By.cssSelector("input.login"));
By XPath
XPath 代表 XML 路径语言。它是一种用于从 XML 文档中选择节点的查询语言。XPath 基于 XML 文档的树表示,并提供通过使用各种条件选择节点来在树中导航的功能。
XPath stands for XML path language. It is a query language for selecting nodes from an XML document. XPath is based on the tree representation of XML documents and provides the ability to navigate around the tree by selecting nodes using a variety of criteria.
driver.findElement(By.xpath(".//*[@id = 'content']/table[1]/tbody/tr/td/table/tbody/tr[2]/td[1]/input")).sendkeys("100");
Selenium - User Interactions
Selenium WebDriver 是 Selenium 工具集中的所有工具中最常用的工具。因此,了解如何使用 Selenium 与 Web 应用程序进行交互非常重要。在此模块中,让我们了解如何使用 Selenium WebDriver 与 GUI 对象进行交互。
Selenium WebDriver is the most frequently used tool among all the tools available in the Selenium tool set. Therefore it is important to understand how to use Selenium to interact with web apps. In this module, let us understand how to interact with GUI objects using Selenium webDriver.
我们需要使用一些基本操作甚至一些高级用户操作与应用程序进行交互,为此需要开发没有预定义命令的用户定义函数。
We need to interact with the application using some basic actions or even some advanced user action by developing user-defined functions for which there are no predefined commands.
以下是针对那些 GUI 对象的不同类型操作 −
Listed below are the different kinds of actions against those GUI objects −
Selenium - Test design techniques
测试设计涉及各种组件。让我们也了解设计框架中涉及的一些重要组件。我们将在本章中学习以下主题 −
There are various components involved in designing the tests. Let us understand some of the important components involved in designing a framework as well. We will learn the following topics in this chapter −
Selenium - TestNG
TestNG 是一种强大的测试框架,它是 JUnit 的增强版,在 TestNG 出现之前就已经长期使用。NG 代表“下一代”。
TestNG is a powerful testing framework, an enhanced version of JUnit which was in use for a long time before TestNG came into existence. NG stands for 'Next Generation'.
TestNG 框架提供以下功能 −
TestNG framework provides the following features −
-
Annotations help us organize the tests easily.
-
Flexible test configuration.
-
Test cases can be grouped more easily.
-
Parallelization of tests can be achieved using TestNG.
-
Support for data-driven testing.
-
Inbuilt reporting.
Installing TestNG for Eclipse
Step 1 − 启动 Eclipse 并选择“安装新软件”。
Step 1 − Launch Eclipse and select 'Install New Software'.
Step 2 − 输入 URL 为“http://beust.com/eclipse”,然后单击“添加”。
Step 2 − Enter the URL as 'http://beust.com/eclipse' and click 'Add'.
Step 3 − 将打开“添加存储库”对话框。输入名称为“TestNG”,然后单击“确定”。
Step 3 − The dialog box 'Add Repository' opens. Enter the name as 'TestNG' and click 'OK'
Step 4 − 单击“全选”,将选择“TestNG”,如下图所示。
Step 4 − Click 'Select All' and 'TestNG' would be selected as shown in the figure.
Step 5 − 单击“下一步”继续。
Step 5 − Click 'Next' to continue.
Step 6 − 查看已选择项,然后单击“下一步”。
Step 6 − Review the items that are selected and click 'Next'.
Step 7 - “接受许可协议”,然后单击“完成”。
Step 7 − "Accept the License Agreement" and click 'Finish'.
Step 8 - TestNG 开始安装,安装进度将如下所示。
Step 8 − TestNG starts installing and the progress would be shown follows.
Step 9 - 由于无法确定软件的有效性,因此会弹出安全警告。单击“确定”。
Step 9 − Security Warning pops up as the validity of the software cannot be established. Click 'Ok'.
Step 10 - 安装程序会提示重新启动 Eclipse 使更改生效。单击“是”。
Step 10 − The Installer prompts to restart Eclipse for the changes to take effect. Click 'Yes'.
Annotations in TestNG
注释正式添加到了 JDK 5 中的 Java 语言,而 TestNG 选择使用注释来注释测试类。以下是使用注释的一些好处。可在 * here* 中找到有关 TestNG 的更多信息。
Annotations were formally added to the Java language in JDK 5 and TestNG made the choice to use annotations to annotate test classes. Following are some of the benefits of using annotations. More about TestNG can be found here
-
TestNG identifies the methods it is interested in by looking up annotations. Hence, method names are not restricted to any pattern or format.
-
We can pass additional parameters to annotations.
-
Annotations are strongly typed, so the compiler will flag any mistakes right away.
-
Test classes no longer need to extend anything (such as TestCase, for JUnit 3).
Sr.No. |
Annotation & Description |
1 |
@BeforeSuite The annotated method will be run only once before all the tests in this suite have run. |
2 |
@AfterSuite The annotated method will be run only once after all the tests in this suite have run. |
3 |
@BeforeClass The annotated method will be run only once before the first test method in the current class is invoked. |
4 |
@AfterClass The annotated method will be run only once after all the test methods in the current class have run. |
5 |
@BeforeTest The annotated method will be run before any test method belonging to the classes inside the <test> tag is run. |
6 |
@AfterTest The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run. |
7 |
@BeforeGroups The list of groups that this configuration method will run before. This method is guaranteed to run shortly before the first test method that belongs to any of these groups is invoked. |
8 |
@AfterGroups The list of groups that this configuration method will run after. This method is guaranteed to run shortly after the last test method that belongs to any of these groups is invoked. |
9 |
@BeforeMethod The annotated method will be run before each test method. |
10 |
@AfterMethod The annotated method will be run after each test method. |
11 |
@DataProvider Marks a method as supplying data for a test method. The annotated method must return an Object[ ][ ] where each Object[ ] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation. |
12 |
@Factory Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[ ]. |
13 |
@Listeners Defines listeners on a test class. |
14 |
@Parameters Describes how to pass parameters to a @Test method. |
15 |
@Test Marks a class or a method as part of the test. |
TestNG-Eclipse Setup
Step 1 - 启动 Eclipse,并创建“New Java Project”(新建 Java 项目),如下所示。
Step 1 − Launch Eclipse and create a 'New Java Project' as shown below.
Step 2 - 输入项目名称,然后单击“Next”(下一步)。
Step 2 − Enter the project name and click 'Next'.
Step 3 - 导航到“Libraries”(库)选项卡,并通过单击“Add External JAR‘s”(添加外部 JAR)添加 Selenium Remote Control 服务器 JAR 文件,如下所示。
Step 3 − Navigate to "Libraries" Tab and Add the Selenium Remote Control Server JAR file by clicking on "Add External JAR’s" as shown below.
Step 4 - 此处显示已添加的 JAR 文件。单击“Add Library”(添加库)。
Step 4 − The added JAR file is shown here. Click 'Add Library'.
Step 5 - 将打开“Add Library”(添加库)对话框。选择“TestNG”,然后在“Add Library”(添加库)对话框中单击“Next”(下一步)。
Step 5 − The 'Add Library' dialog opens. Select 'TestNG' and click 'Next' in the 'Add Library' dialog box.
Step 6 - 已添加的“TestNG”库已添加,并按以下方式显示。
Step 6 − The added 'TestNG' Library is added and it is displayed as shown below.
Step 7 - 创建项目后,项目的结构将按以下方式显示。
Step 7 − Upon creating the project, the structure of the project would be as shown below.
Step 8 - 右键单击“src”文件夹,然后选择 New(新建)>> Other(其他)。
Step 8 − Right-click on 'src' folder and select New >> Other.
Step 9 − 选择“TestNG”并单击“Next”。
Step 9 − Select 'TestNG' and click 'Next'.
Step 10 − 选择“源文件夹”名称并单击“确定”。
Step 10 − Select the 'Source Folder' name and click 'Ok'.
Step 11 − 选择“包名称”和“类名称”,然后单击“完成”。
Step 11 − Select the 'Package name', the 'class name', and click 'Finish'.
Step 12 − 将显示包资源管理器和创建的类。
Step 12 − The Package explorer and the created class would be displayed.
First Test in TestNG
现在,让我们开始使用 TestNG 进行脚本编写。让我们使用与我们用来理解 WebDriver 相同的例子进行脚本编写。我们将使用演示应用程序 www.calculator.net ,并进行百分比计算。
Now let us start scripting using TestNG. Let us script for the same example that we used for understanding the WebDriver. We will use the demo application, www.calculator.net, and perform percent calculator.
在以下测试中,您会注意到没有 main 方法,因为 testNG 将驱动程序执行流程。在初始化 driver 后,它将执行“@BeforeTest”方法,其次是“@Test”,然后是“@AfterTest”。请注意,一个类中可以有多个“@Test”注释,但“@BeforeTest”和“@AfterTest”只能出现一次。
In the following test, you will notice that there is NO main method, as testNG will drive the program execution flow. After initializing the driver, it will execute the '@BeforeTest' method followed by '@Test' and then '@AfterTest'. Please note that there can be any number of '@Test' annotation in a class but '@BeforeTest' and '@AfterTest' can appear only once.
package TestNG;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TestNGClass {
WebDriver driver = new FirefoxDriver();
@BeforeTest
public void launchapp() {
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to("http://www.calculator.net");
driver.manage().window().maximize();
}
@Test
public void calculatepercent() {
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id='menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
driver.findElement(By.xpath(".//*[@id='content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id='content']/p[2]/span/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
if(result.equals("5")) {
System.out.println(" The Result is Pass");
} else {
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void terminatetest() {
driver.close();
}
}
Execution
要执行,右键单击创建的 XML,然后选择“Run As” >> “TestNG Suite”
To execute, right click on the created XML and select "Run As" >> "TestNG Suite"
Result Analysis
输出将传送到控制台,它将显示如下。控制台输出还包含执行摘要。
The output is thrown to the console and it would appear as shown below. The console output also has an execution summary.
还可以在其他选项卡中看到 TestNG 的结果。单击如下所示的“HTML Report View”按钮。
The result of TestNG can also be seen in a different tab. Click on 'HTML Report View' button as shown below.
HTML 结果将显示如下。
The HTML result would be displayed as shown below.
Selenium - Grid
Selenium Grid 是一个跨多个物理或虚拟机分发测试的工具,以便我们可以并行(同时)执行脚本。通过提供快速准确的反馈,它极大地加速了跨浏览器和跨平台的测试过程。
Selenium Grid is a tool that distributes the tests across multiple physical or virtual machines so that we can execute scripts in parallel (simultaneously). It dramatically accelerates the testing process across browsers and across platforms by giving us quick and accurate feedback.
Selenium Grid 允许我们并行执行 WebDriver 或 Selenium Remote Control 测试的多实例,它们使用相同的代码库,因此代码不必存在于执行它们的系统上。selenium-server-standalone 包包括 Hub、WebDriver 和 Selenium RC,以在网格中执行脚本。
Selenium Grid allows us to execute multiple instances of WebDriver or Selenium Remote Control tests in parallel which uses the same code base, hence the code need NOT be present on the system they execute. The selenium-server-standalone package includes Hub, WebDriver, and Selenium RC to execute the scripts in grid.
Selenium Grid 具有 Hub 和 Node。
Selenium Grid has a Hub and a Node.
-
Hub − The hub can also be understood as a server which acts as the central point where the tests would be triggered. A Selenium Grid has only one Hub and it is launched on a single machine once.
-
Node − Nodes are the Selenium instances that are attached to the Hub which execute the tests. There can be one or more nodes in a grid which can be of any OS and can contain any of the Selenium supported browsers.
Architecture
下图显示了 Selenium Grid 的架构。
The following diagram shows the architecture of Selenium Grid.
Working with Grid
为了与 Grid 一起使用,我们需要遵循某些协议。以下列出了此过程中涉及的主要步骤 -
In order to work with the Grid, we need to follow certain protocols. Listen below are the major steps involved in this process −
-
Configuring the Hub
-
Configuring the Nodes
-
Develop the Script and Prepare the XML File
-
Test Execution
-
Result Analysis
让我们详细讨论每一步。
Let us discuss each of these steps in detail.
Configuring the Hub
Step 1 − 从 http://docs.seleniumhq.org/download/ 下载最新的 Selenium 服务器独立 JAR 文件。单击版本即可下载,如下所示。
Step 1 − Download the latest Selenium Server standalone JAR file from http://docs.seleniumhq.org/download/. Download it by clicking on the version as shown below.
Step 2 − 使用以下命令启动 Selenium Server,即可启动 Hub。现在,我们将使用端口“4444”来启动 Hub。
Step 2 − Start the Hub by launching the Selenium Server using the following command. Now we will use the port '4444' to start the hub.
Note − 确保端口号 4444 上没有任何其他应用程序正在运行。
Note − Ensure that there are no other applications that are running on port# 4444.
java -jar selenium-server-standalone-2.25.0.jar -port 4444 -role hub -nodeTimeout 1000
Step 3 − 现在,从 Hub(执行步骤 2 的系统)打开浏览器,并导航至 URL http//localhost:4444。
Step 3 − Now open the browser and navigate to the URL http//localhost:4444 from the Hub (The system where you have executed Step#2).
Step 4 − 现在,单击“控制台”链接,然后单击“查看配置”。Hub 的配置将显示如下。目前,我们没有任何节点,因此我们看不到详细信息。
Step 4 − Now click on the 'console' link and click 'view config'. The config of the hub would be displayed as follows. As of now, we haven’t got any nodes, hence we will not be able to see the details.
Configuring the Nodes
Step 1 − 登录到节点(你希望在其中执行脚本的节点),并将“selenium-server-standalone-2.42.2”放在文件夹中。我们需要在启动节点时指向 selenium-server-standalone JAR。
Step 1 − Logon to the node (where you would like to execute the scripts) and place the 'selenium-server-standalone-2.42.2' in a folder. We need to point to the selenium-server-standalone JAR while launching the nodes.
Step 2 − 使用以下命令启动 FireFox 节点。
Step 2 − Launch FireFox Node using the following below command.
java -jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role node -hub http://10.30.217.157:4444/grid/register
-browser browserName = firefox -port 5555
其中,
Where,
D:\JAR\selenium-server-standalone-2.42.2.jar = Selenium Server 独立 JAR 文件的路径(在节点计算机上)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
[role="bare"] [role="bare"]http://10.30.217.157:4444 = Hub 的 IP 地址,4444 是 Hub 的端口
[role="bare"]http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = firefox(在节点上指定浏览器名称的参数)
browserName = firefox (Parameter to specify the Browser name on Nodes)
5555 = Firefox 节点将启动并运行的端口。
5555 = Port on which Firefox Node would be up and running.
Step 3 − 执行命令后,返回 Hub。导航至 URL - [role="bare"] [role="bare"]http://10.30.217.157:4444 ,Hub 现在会显示附加到它的节点。
Step 3 − After executing the command, come back to the Hub. Navigate to the URL - [role="bare"]http://10.30.217.157:4444 and the Hub would now display the node attached to it.
Step 4 − 现在,让我们启动 Internet Explorer 节点。要启动 IE 节点,我们需要在节点计算机上下载 Internet Explorer 驱动程序。
Step 4 − Now let us launch the Internet Explorer Node. For launching the IE Node, we need to have the Internet Explorer driver downloaded on the node machine.
Step 5 − 要下载 Internet Explorer 驱动程序,请导航至 http://docs.seleniumhq.org/download/ 根据操作系统的架构下载相应的文件。下载后,解压缩 exe 文件,并将其放在一个启动 IE 节点时必须引用的文件夹中。
Step 5 − To download the Internet Explorer driver, navigate to http://docs.seleniumhq.org/download/ and download the appropriate file based on the architecture of your OS. After you have downloaded, unzip the exe file and place in it a folder which has to be referred while launching IE nodes.
Step 6 − 使用以下命令启动 IE。
Step 6 − Launch IE using the following command.
C:\>java -Dwebdriver.ie.driver = D:\IEDriverServer.exe
-jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role webdriver -hub http://10.30.217.157:4444/grid/register
-browser browserName = ie,platform = WINDOWS -port 5558
其中,
Where,
D:\IEDriverServer.exe = 下载的 IE 驱动程序的路径(在节点计算机上)
D:\IEDriverServer.exe = The location of the downloaded the IE Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Selenium Server 独立 JAR 文件的路径(在节点计算机上)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
[role="bare"] [role="bare"]http://10.30.217.157:4444 = Hub 的 IP 地址,4444 是 Hub 的端口
[role="bare"]http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = ie(在节点上指定浏览器名称的参数)
browserName = ie (Parameter to specify the Browser name on Nodes)
5558 = IE 节点启动并运行的端口。
5558 = Port on which IE Node would be up and running.
Step 7 − 执行命令后,返回 Hub。导航至 URL - [role="bare"] [role="bare"]http://10.30.217.157:4444 ,Hub 现在会显示附加到它的 IE 节点。
Step 7 − After executing the command, come back to the Hub. Navigate to the URL - [role="bare"]http://10.30.217.157:4444 and the Hub would now display the IE node attached to it.
Step 8 - 现在让我们启动 Chrome Node。要启动 Chrome Node,我们需要在节点机器上下载 Chrome 驱动程序。
Step 8 − Let us now launch Chrome Node. For launching the Chrome Node, we need to have the Chrome driver downloaded on the node machine.
Step 9 - 要下载 Chrome 驱动程序,请导航至 http://docs.seleniumhq.org/download/ ,然后导航到第三方浏览器驱动程序区域,并单击版本号“2.10”,如下所示。
Step 9 − To download the Chrome Driver, navigate to http://docs.seleniumhq.org/download/ and then navigate to Third Party Browser Drivers area and click on the version number '2.10' as shown below.
Step 10 - 根据操作系统的类型下载驱动程序。我们将在 Windows 环境中执行它,因此我们将下载 Windows Chrome 驱动程序。下载完成后,解压 exe 文件并将其放置在启动 chrome 节点时需要引用的文件夹中。
Step 10 − Download the driver based on the type of your OS. We will execute it on Windows environment, hence we will download the Windows Chrome Driver. After you have downloaded, unzip the exe file and place it in a folder which has to be referred while launching chrome nodes.
Step 11 - 使用以下命令启动 Chrome。
Step 11 − Launch Chrome using the following command.
C:\>java -Dwebdriver.chrome.driver = D:\chromedriver.exe
-jar D:\JAR\selenium-server-standalone-2.42.2.jar
-role webdriver -hub http://10.30.217.157:4444/grid/register
-browser browserName = chrome, platform = WINDOWS -port 5557
其中,
Where,
D:\chromedriver.exe = 下载的 Chrome 驱动程序(在节点机器上)的位置
D:\chromedriver.exe = The location of the downloaded the chrome Driver(on the Node Machine)
D:\JAR\selenium-server-standalone-2.42.2.jar = Selenium Server 独立 JAR 文件的路径(在节点计算机上)
D:\JAR\selenium-server-standalone-2.42.2.jar = Location of the Selenium Server Standalone Jar File(on the Node Machine)
[role="bare"] [role="bare"]http://10.30.217.157:4444 = Hub 的 IP 地址,4444 是 Hub 的端口
[role="bare"]http://10.30.217.157:4444 = IP Address of the Hub and 4444 is the port of the Hub
browserName = chrome(指定节点上浏览器名称的参数)
browserName = chrome (Parameter to specify the Browser name on Nodes)
5557 = chrome 节点将启动并运行的端口。
5557 = Port on which chrome Node would be up and running.
Step 12 - 执行命令后,回到 Hub。导航到 URL - [role="bare"] [role="bare"]http://10.30.217.157:4444 ,Hub 现在将显示附加到它的 Chrome 节点。
Step 12 − After executing the command, come back to the Hub. Navigate to the URL - [role="bare"]http://10.30.217.157:4444 and the Hub would now display the chrome node attached to it.
Develop the Script and Prepare the XML File
Step 1 - 我们将使用 TestNG 开发测试。在以下示例中,我们将使用远程 webDriver 启动这些浏览器中的每一个。它可以将它们的能力传递给驱动程序,以便驱动程序具有在节点上执行的所有信息。
Step 1 − We will develop a test using TestNG. In the following example, we will launch each one of those browsers using remote webDriver. It can pass on their capabilities to the driver so that the driver has all information to execute on Nodes.
浏览器参数将从“XML”文件中传递。
The Browser Parameter would be passed from the "XML" file.
package TestNG;
import org.openqa.selenium.*;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import java.net.MalformedURLException;
public class TestNGClass {
public WebDriver driver;
public String URL, Node;
protected ThreadLocal<RemoteWebDriver> threadDriver = null;
@Parameters("browser")
@BeforeTest
public void launchapp(String browser) throws MalformedURLException {
String URL = "http://www.calculator.net";
if (browser.equalsIgnoreCase("firefox")) {
System.out.println(" Executing on FireFox");
String Node = "http://10.112.66.52:5555/wd/hub";
DesiredCapabilities cap = DesiredCapabilities.firefox();
cap.setBrowserName("firefox");
driver = new RemoteWebDriver(new URL(Node), cap);
// Puts an Implicit wait, Will wait for 10 seconds before throwing exception
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("chrome")) {
System.out.println(" Executing on CHROME");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("chrome");
String Node = "http://10.112.66.52:5557/wd/hub";
driver = new RemoteWebDriver(new URL(Node), cap);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else if (browser.equalsIgnoreCase("ie")) {
System.out.println(" Executing on IE");
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setBrowserName("ie");
String Node = "http://10.112.66.52:5558/wd/hub";
driver = new RemoteWebDriver(new URL(Node), cap);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
// Launch website
driver.navigate().to(URL);
driver.manage().window().maximize();
} else {
throw new IllegalArgumentException("The Browser Type is Undefined");
}
}
@Test
public void calculatepercent() {
// Click on Math Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[3]/a")).click();
// Click on Percent Calculators
driver.findElement(By.xpath(".//*[@id = 'menu']/div[4]/div[3]/a")).click();
// Enter value 10 in the first number of the percent Calculator
driver.findElement(By.id("cpar1")).sendKeys("10");
// Enter value 50 in the second number of the percent Calculator
driver.findElement(By.id("cpar2")).sendKeys("50");
// Click Calculate Button
// driver.findElement(By.xpath(".//*[@id = 'content']/table/tbody/tr/td[2]/input")).click();
// Get the Result Text based on its xpath
String result =
driver.findElement(By.xpath(".//*[@id = 'content']/p[2]/span/font/b")).getText();
// Print a Log In message to the screen
System.out.println(" The Result is " + result);
if(result.equals("5")) {
System.out.println(" The Result is Pass");
} else {
System.out.println(" The Result is Fail");
}
}
@AfterTest
public void closeBrowser() {
driver.quit();
}
}
Step 2 - 浏览器参数将通过 XML 传递。在项目文件夹下创建一个 XML。
Step 2 − The Browser parameter will be passed using XML. Create an XML under the project folder.
Step 3 - 从“常规”中选择“文件”,然后单击“下一步”。
Step 3 − Select 'File' from 'General' and click 'Next'.
Step 4 - 输入文件名,然后单击“完成”。
Step 4 − Enter the name of the file and click 'Finish'.
Step 5 - TestNg.XML 如下所示创建在项目文件夹下。
Step 5 − TestNg.XML is created under the project folder as shown below.
Step 6 - XML 文件的内容如下所示。我们创建 3 个测试,将它们放入套件中,并指定 parallel="tests",以便所有测试都将并行执行。
Step 6 − The contents of the XML file are shown below. We create 3 tests and put them in a suite and mention parallel="tests" so that all the tests would be executed in parallel.
<?xml version = "1.0" encoding = "UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name = "Suite" parallel = "tests">
<test name = "FirefoxTest">
<parameter name = "browser" value = "firefox" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
<test name = "ChromeTest">
<parameter name = "browser" value = "chrome" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
<test name = "IETest">
<parameter name = "browser" value = "ie" />
<classes>
<class name = "TestNG.TestNGClass" />
</classes>
</test>
</suite>
Test Execution
Step 1 - 选择创建的 XML;右键单击,然后选择“以…运行”>>“TestNG 套件”。
Step 1 − Select the created XML; right-click and choose 'Run As' >> 'TestNG Suite'.
Step 2 - 现在打开节点,我们在其中启动了所有浏览器节点。您会同时看到正在执行的所有三个浏览器。
Step 2 − Now open the Node, where we have launched all the browser nodes. You will see all the three browsers in execution simultaneously.
Result Analysis
Step 1 - 完成执行后,我们可以像其他任何执行一样分析结果。结果摘要以控制台中打印,如下面的快照所示。
Step 1 − Upon completing the execution, we can analyze the result like any other execution. The result summary is printed in the console as shown in the following snapshot.
Step 2 - 导航到“正在运行的套件的结果”选项卡,TestNG 将显示结果摘要,如下所示。
Step 2 − Navigate to the 'Results of Running Suite' Tab and TestNG would display the result summary as shown below.
{s0} − 生成 HTML 后,我们将能够以 HTML 格式查看测试结果。
Step 3 − Upon generating the HTML, we will be able to see the test results in HTML format.