`

Selenium Tutorial -10 Implementation of Our First WebDriver Script

 
阅读更多

http://www.softwaretestinghelp.com/selenium-webdriver-tutorial-10/

 

In the previous two tutorials, we made you acquainted with the basic architecture and features of WebDriver and the infrastructure required to get started with Selenium WebDriver. Assuming that you all might have set up the system with all the necessary utilities and packages,we will move further with the implementation of our first WebDriver test script.

Therefore, motioning ahead with the consequent Selenium WebDriver tutorial, we would be creating WebDriver script. We would also scatter the light on the basic and commonly usedWebDriver commands. We would also learn about the locating strategies of UI elements and their inclusion in the test scripts. We would also study Get Commands in the detail.

Selenium WebDriver Tutorial

Script Creation

For script creation, we would be using “Learning_Selenium” project created in the previous tutorial and “gmail.com” as the application under test (AUT).

Scenario:

  • Launch the browser and open “Gmail.com”.
  • Verify the title of the page and print the verification result.
  • Enter the username and Password.
  • Click on the Sign in button.
  • Close the web browser.

Step 1: Create a new java class named as “Gmail_Login” under the “Learning_Selenium” project.

Step 2: Copy and paste the below code in the “Gmail_Login.java” class.

1 import org.openqa.selenium.By;
2 import org.openqa.selenium.WebDriver;
3 import org.openqa.selenium.WebElement;
4 import org.openqa.selenium.firefox.FirefoxDriver;
5  
6 public class Gmail_Login {
7 /**
8 * @param args
9 */
10        public static void main(String[] args) {
11               
12 // objects and variables instantiation
13               WebDriver driver = new FirefoxDriver();
14               String appUrl ="https://accounts.google.com";
15               
16 // launch the firefox browser and open the application url
17               driver.get(appUrl);
18               
19 // maximize the browser window
20               driver.manage().window().maximize();
21               
22 // declare and initialize the variable to store the expected title of the webpage.
23               String expectedTitle = " Sign in - Google Accounts ";
24               
25 // fetch the title of the web page and save it into a string variable
26               String actualTitle = driver.getTitle();
27               
28 // compare the expected title of the page with the actual title of the page and print the result
29               if (expectedTitle.equals(actualTitle))
30               {
31                      System.out.println("Verification Successful - The correct title is displayed on the web page.");
32               }
33              else
34               {
35                      System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
36               }
37  
38 // enter a valid username in the email textbox
39               WebElement username = driver.findElement(By.id("Email"));
40               username.clear();
41               username.sendKeys("TestSelenium");
42               
43 // enter a valid password in the password textbox
44               WebElement password = driver.findElement(By.id("Passwd"));
45               password.clear();
46               password.sendKeys("password123");
47               
48 // click on the Sign in button
49               WebElement SignInButton = driver.findElement(By.id("signIn"));
50               SignInButton.click();
51               
52 // close the web browser
53               driver.close();
54               System.out.println("Test script executed successfully.");
55               
56 // terminate the program
57               System.exit(0);
58        }
59 }

The above code is equivalent to the textual scenario presented earlier.

Code Walkthrough

Import Statements:

1 import org.openqa.selenium.WebDriver;
2 import org.openqa.selenium.firefox.FirefoxDriver;
3 import org.openqa.selenium.WebElement;
4 import org.openqa.selenium.By;

Prior to the actual scripting, we need to import the above packages:

import org.openqa.selenium.WebDriver – References the WebDriver interface which is required to instantiate a new web browser.

import org.openqa.selenium.firefox.FirefoxDriver – References the FirefoxDriver class that is required instantiate a Firefox specific driver on the browser instance instantiated using WebDriver interface.

import org.openqa.selenium.WebElement – References to the WebElement class which is required to instantiate a new web element.

import org.openqa.selenium.By – References to the By class on which a locator type is called.

As and when our project would grow, it is evident and logical that we might have to introduce several other packages for more complex and distinct functionalities like excel manipulations, database connectivity, logging, assertions etc.

Object Instantiation

WebDriver driver = new FirefoxDriver();

We create a reference variable for WebDriver interface and instantiate it using FirefoxDriver class. A default Firefox profile will be launched which means that no extensions and plugins would be loaded with the Firefox instance and that it runs in the safe mode.

Launching the Web browser

driver.get(appUrl);

get() method is called on the WebDriver instance to launch a fresh web browser instance. The string character sequence passed as a parameter into the get() method redirects the launched web browser instance to the application URL.

Maximize Browser Window

driver.manage().window().maximize();

The maximize() method is used to maximize the browser window soon after it is re-directed to the application URL.

Fetch the page Title

driver.getTitle();

The getTitle() method is used to fetch the title of the current web page. Thus, the fetched title can be loaded to a string variable.

Comparison between Expected and Actual Values:

1 if (expectedTitle.equals(actualTitle))
2               {
3                      System.out.println("Verification Successful - The correct title is displayed on the web page.");
4               }
5               else
6               {
7                      System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
8               }

The above code uses the conditional statement java constructs to compare the actual value and the expected value. Based on the result obtained, the print statement would be executed.

WebElement Instantiation

WebElement username = driver.findElement(By.id(“Email”));

In the above statement, we instantiate the WebElement reference with the help of “driver.findElement(By.id(“Email”))”. Thus, username can be used to reference the Email textbox on the user interface every time we want to perform some action on it.

------------

Clear Command

username.clear();

The clear() method/command is used to clear the value present in the textbox if any. It also clears the default placeholder value.

sendKeys Command

username.sendKeys(“TestSelenium “);

The sendKeys() method/command is used to enter/type the specified value (within the parentheses ) in the textbox. Notice that thesendKeys() method is called on the WebElement object which was instantiated with the help of element property corresponding to the UI element.

The above block of code enters the string “TestSelenium” inside the Email textbox on the Gmail application.

sendKeys is one of the most popularly used commands across the WebDriver scripts.

Click Command

SignInButton.click();

Like sendKeys(), click() is another excessively used command to interact with the web elements. Click() command/method is used to click on the web element present on the web page.

The above block of code clicks on the “Sign in” button present on the Gmail application.

Notes:

  • Unlike sendKeys() method, click() methods can never be parameterized.
  • At times, clicking on a web element may load a new page altogether. Thus to sustain such cases, click() method is coded in a way to wait until the page is loaded.

Close the Web Browser

driver.close();

The close() is used to close the current browser window.

Terminate the Java Program

System.exit(0);

The Exit() method terminates the Java program forcefully. Thus, remember to close all the browser instances prior terminating the Java Program.

Test Execution

The test script or simply the java program can be executed in the following ways:

#1. Under the Eclipse’s menu bar, there is an icon to execute the test script. Refer the following figure.

WebDriver tutorial 1

Make a note that only the class which is selected would be executed.

#2. Right click anywhere inside the class within the editor, select “Run As” option and click on the “Java Application”.

#3. Another shortcut to execute the test script is – Press ctrl + F11.

At the end of the execution cycle, the print statement “Test script executed successfully.” can be found in the console.

Locating Web Elements

Web elements in WebDriver can be located and inspected in the same way as we did in the previous tutorials of Selenium IDE. Selenium IDE and Firebug can be used to inspect the web element on the GUI. It is highly suggested to use Selenium IDE to find the web elements. Once the web element is successfully found, copy and paste the target value within the WebDriver code. The types of locators and the locating strategies are pretty much the same except for the syntax and their application.

In WebDriver, web elements are located with the help of the dynamic finders (findElement(By.locatorType(“locator value”))).

Sample Code:

driver.findElement(By.id(“Email”));

WebDriver tutorial 2

Locator Types and their Syntax

Locator Type Syntax Description
id driver.findElement
(By.id(“ID_of_Element”))
Locate by value of 
the “id” attribute
className driver.findElement
(By.className
(“Class_of_Element”))
Locate by value of 
the “class” attribute
linkText driver.findElement
(By.linkText(“Text”))
Locate by value of the
text of the hyperlink
partialLinkText driver.findElement
(By.partialLinkText
(“PartialText”))
Locate by value of the
sub-text of the hyperlink
name driver.findElement
(By.name
(“Name_of_Element”))
Locate by value of the
“name” attribute
xpath driver.findElement
(By.xpath(“Xpath”))
Locate by value 
of the xpath
cssSelector driver.findElement
(By.cssSelector
(“CSS Selector”))
Locate by value of
the CSS selector
tagName driver.findElement
(By.tagName(“input”))
Locate by value of
its tag name

Conclusion

In this tutorial, we developed an automation script using WebDriver and Java. We also discussed the various components that constitute a WebDriver script.

Here are the cruxes of this Selenium WebDriver Tutorial:

  • Prior to the actual scripting, we need to import a few packages to be able to create a WebDriver script.
    • importopenqa.selenium.By;
    • importopenqa.selenium.WebDriver;
    • importopenqa.selenium.WebElement;
    • importopenqa.selenium.firefox.FirefoxDriver;
  • get() method used to launch a fresh web browser instance. The character sequence passed as a parameter into the get() method redirects the launched web browser instance to the application URL.
  • The maximize() method is used to maximize the browser window.
  • The clear() method is used to clear the value present in the textbox if any.
  • The sendKeys() method is used to enter the specified value in the textbox.
  • Click() method is used to click on the web element present on the web page.
  • In WebDriver, web elements can be located using Dynamic finders.
  • The following are the available locator types:
    • id
    • className
    • name
    • xpath
    • cssSelector
    • linkText
    • partialLinkText
    • tagName

Moving ahead, in the next tutorial, we would shift our focus towards a framework that aids to Automation testing known as TestNG. We would have a detailed study on the various kinds of the annotations provided by the framework.

Next tutorial #11: Before diving deep into Frameworks we will see details about JUnit – an open source unit testing tool. Most of the programmers use JUnit as it is easy and does not take much effort to test. This tutorial will give an insight about JUnit and its usage in selenium script.

A remark for the readers: While our next tutorial of the Selenium series is in the processing mode, readers can start creating their own basic WebDriver scripts. For more advance scripts and concepts, we will have various other Selenium WebDriver tutorials coming up in this series.

分享到:
评论

相关推荐

    php-selenium-client, PHP与 Selenium WebDriver API的交互.zip

    php-selenium-client, PHP与 Selenium WebDriver API的交互 php-seleniumclientPHP与 Selenium WebDriver API的交互##Description这个库允许在PHP中与 selenium 服务器V2交互。 它通过官方JsonWireProtocol与API

    selenium-server-standalone和Selenium-java的jar包

    首先,**selenium-server-standalone.jar**是Selenium WebDriver的核心组件,包含了WebDriver服务器的所有依赖。这个jar包让你能够与浏览器进行交互,执行各种网页操作,如点击按钮、填写表单、导航等。它提供了不同...

    selenium-webdriver介绍PPT

    selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创selenium-webdriver原创

    selenium-webdriver-2.40.0.gem

    selenium-webdriver-2.40.0.gem

    selenium-selenium-4.5.0.zip源码

    在 `selenium-selenium-4.5.0.zip` 源码中,我们可以深入理解 Selenium 的内部实现,包括以下关键部分: 1. **WebDriver**: 这部分包含了各个浏览器驱动(如 ChromeDriver、GeckoDriver)的实现,它们作为桥梁,...

    ruby+selenium-webdriver测试--第一个例子源代码

    Ruby+Selenium-Webdriver是一个强大的自动化测试工具组合,用于模拟真实用户在浏览器中与网页进行交互。Ruby是一种动态、面向对象的编程语言,而Selenium WebDriver是一个开源的自动化测试框架,支持多种浏览器和...

    selenium-server-standalone-2.40

    在这个名为 "selenium-server-standalone-2.40" 的压缩包中,包含了Selenium Server的独立版本以及相关的Java库。 1. **Selenium Server Standalone**: Selenium Server Standalone是Selenium的核心组件之一,它...

    selenium-server-standalone-2.45.0和selenium-java-2.45.0(含srcs)

    总结起来,"selenium-server-standalone-2.45.0" 和 "selenium-java-2.45.0(含srcs)" 提供了Selenium的核心组件,支持Java环境下的WebDriver自动化测试,同时包含了源码以便于深入学习和定制。它们是Web应用自动化...

    selenium-server-standalone-4.0.0-alpha-2.zip

    标题 "selenium-server-standalone-4.0.0-alpha-2.zip" 指的是 Selenium 的一个服务器独立版本的归档文件,该版本为 4.0.0 的 Alpha 2 版本。Selenium 是一个广泛使用的自动化测试工具,主要用于 Web 应用程序的测试...

    selenium-java-2.44.0、selenium-java-2.44.0-srcs、selenium-server-standalone-2.44.0

    接着,`selenium-java-2.44.0-srcs.jar` 包含的是Selenium WebDriver的Java源代码。这对于开发者来说非常有价值,因为它允许深入研究Selenium的内部工作原理,调试问题,或者根据需要自定义和扩展其功能。源代码也...

    selenium-java 3.7.1.jar

    【Selenium-Java 3.7.1.jar】是一个关键组件,主要用于自动化Web应用程序的测试。这个特定的版本,3.7.1,是Selenium WebDriver的一个Java绑定,它允许开发者使用Java语言来编写测试脚本,从而实现对浏览器的自动化...

    selenium-server-standalone-2.53.1.jar

    selenium-server-standalone-2.53.1.jar用于支持selenium webdriver的开发,也可用于分布式测试连接

    selenium-webdriver-2.45.0.gem

    selenium-webdriver-2.45.0.gem

    selenium-server-standalone-3.0.0JAR包

    `selenium-server-standalone.jar` 通常用作测试服务器,通过 WebDriver API 接口与浏览器进行交互,执行自动化测试脚本。 在描述中提到了 `java-client-3.3.0`,这是 Selenium Java 客户端驱动程序的版本,它提供...

    Selenium-WebDriver-Java:Selenium-WebDriver-Java的示例

    Selenium-WebDriver-Java Selenium-WebDriver-Java的示例

    selenium-dotnet-3.5.2 C# webdriver

    【Selenium-dotnet-3.5.2 C# Webdriver】是用于自动化Web浏览器操作的开源工具,尤其在软件测试领域广泛应用。Selenium支持多种编程语言,包括C#,并且与.NET Framework兼容,使得.NET开发者可以方便地进行网页自动...

    selenium-server-standalone-3.4.0&selenium;-java-3.4.0.jar

    `selenium-server-standalone-3.4.0` 是 Selenium 的独立服务器版本,包含了所有必需的组件,包括 WebDriver、Remote WebDriver 以及各种浏览器驱动程序。它使得开发者无需单独安装各个浏览器驱动,即可在多种浏览器...

    selenium-java-2.47.1.zip

    这个压缩包 "selenium-java-2.47.1.zip" 包含了Selenium的Java版本,具体是2.47.1的更新,发布于2015年8月。这个版本在当时是一个稳定且广泛使用的版本,它提供了丰富的API,支持多种浏览器,并且可以与各种测试框架...

    selenium-server-standalone-2.44.0.jar

    selenium-server-standalone-2.44.0, selenium最新服务器,

    selenium-webdriver-api文档

    这个文档,`selenium-API-2.12.chm`,是针对Selenium WebDriver 2.12版本的详细指南,对于理解和使用WebDriver API至关重要。 ### 1. WebDriver 概念 WebDriver 是一种接口,它提供了对浏览器的直接控制,支持多种...

Global site tag (gtag.js) - Google Analytics