Introduction to Selenium (Java Track)

From Training Material
Jump to navigation Jump to search


Nobleprog.svg


Introduction to Selenium (Java Track)


Introduction to Selenium

Selenium consists of a set of tools

  • Selenium IDE
  • Firefox add-on
  • Simple record and play back of browser interactions
  • Selenium WebDriver
  • Create programs to automate web browser's
  • There are programmatic drivers for most of the common Browsers
  • i.e. Firefox, Internet Explorer, Safari, Chrome, etc.
  • Given the various web browser drivers - thus the name WebDriver

Selenium IDE Introduction

  • Selenium IDE is useful for building starting test cases or test suites
It allows recording of user interactions with the browser (Firefox)
It allows building of test cases by adding commands and HTML elements they will act upon
It allows the test cases to be run (to make sure they work)
It allows the test cases to be saved in various languages such as Java

Selenium WebDriver Introduction

  • Selenium WebDriver is a tool that automates browsers
  • Automation refers to giving commands to a browser
  • For example: browser open, browser go to web site page, browser give me the tags of this type, browser close.
  • When given the commands the browser can be watched as it opens, goes to pages, closes, etc.

  • Selenium WebDriver is a tool that can make assertions about web page data and tags
  • Assertions when using Java are from the Java JUnit modules
  • Assertions are questions that that can be answered as true or false
  • Does this web page have the following data?
  • Does this web page have the following HTML tag?
  • Does this web page exist?
  • Assertions can be failed

  • Selenium WebDriver is a tool that can put data into form inputs on a web page
  • Put in a username and password
  • Put in a search term
  • Fill out a profile for a user

  • This makes Selenium WebDriver a very powerful tool for the testing of web pages and content


Set Up a Tomcat server for Testing

Understanding the development process

  • It may be a good idea to have a web server
It helps to have HTML elements isolated so you can determine how to set up Selenium commands
It helps in working with AJAX elements to have them isolated
It helps in training to have a server with examples that WebDriver Or Selenium IDE can run against
  • Tomcat is open source and fairly easy to set up

Set up a Tomcat development web server

  • The web server builds and serves web pages to browsers
    • Browsers - Firefox, Chrome, Internet Explorer, Safari, etc.
  • A Development web server generally is on a developer's computer
    • The code base is put onto the server such that the developer can step through web pages that are built by the server.
    • These days this is usually done in an Integrated Development Environment (IDE)
      • Eclipse
      • Netbeans
      • Visual Studio
      • Intellij

Install Java JDK

  • Go to the oracle.com Java downloads page referenced below and download the latest version of the Java JDK
Presently this is version 8u66 (make sure that you get the JDK
For Windows get the 64 (x64) or 32(x86) bit version depending upon your type of system
Is your computer a 64 bit or 32 bit computer?
Windows see Windows running 64 or 32 bit?
Mac see Mac OS X running 64 or 32 bit?
  • Install Java using the installer for your operating system type (Windows, Mac OS X)
  • Put the Java folder into your environment's path variable
Make sure you do not delete your path by mistake, it is hard to get it back
Hands on Exercise - Install Java JDK:
Using the following document install the Java JDK that corresponds to the type of Operating system that exists on your computer (Windows, Mac OS, Linux x64, etc.). The installation steps will be approximately the same for each operating system.
Installing the JDK
Reference

Oracle Java SE Downloads

Install Eclipse

  • Go to the Eclipse.org download page and get the latest version of Eclipse (see link below in References)
  • Extract the zip file into a folder in a well known location
  • Create a workspace folder in a well known location
    • Usually it is best to create a folder and place both Eclipse and the workspace in that folder
    • So that they are together
  • Create a shortcut to the eclipse.exe file on the desktop (at least for Windows)
Hands on Exercise - Install Eclipse:
Using the following instructions install Eclipse on your computer. Eclipse is an Integrated Development Environment commonly used by developers. Installation steps will be approximately the same for all operating systems. There is only one installation zip file for all operating systems.
Installing Eclipse
Reference

Eclipse Download Page

Install Apache Tomcat

Hands on Exercise - Install a Web Server
Install Tomcat on Windows
Install a WAR file into Tomcat Selenium Testing WAR
The WAR file goes into the Tomcat webapps directory

Create a small web application for use in testing

HTML Static Pages

Servlets

  • Tomcat has a Servlet Container. The Servlet Container:
    • Gets HTTP requests from clicks on web pages (usually)
    • Keeps state for the user through cookie JSESSIONID, web pages are stateless
    • Delegates the request to a servlet.
    • Returns a response to the requester.
  • A servlet:
    • Is a component of a Java Web Application (usually)
    • Is a Java class that extends HttpServlet (usually)
    • Is configured to handle requests for a specific web page
    • Gets requests from the Servlet Container
    • Give responses back to the Servlet Container
Hands on Exercise
Step 1 - Click and save the Web Project WAR file that is zipped below
Step 2 - Extract the WAR file from the zip
Step 3 - Start Eclipse if it is not already running
Step 4 - Import the WAR file below into Eclipse
Step 5 - Go over the examples of JSPs and Servlets with the instructor
Note that "Create a Servlet and WAR file in Eclipse" and "Create an Eclipse Web Project" are discussions on how to create web projects and Servlets. The WAR file to be imported was created by making a web project and then creating servlets and JSPs within that project. Those files were then export as the WAR.
Install a WAR file into Tomcat Selenium Testing WAR
Note that this is the same file that was installed above no need to do it twice
Create a Servlet and WAR file in Eclipse
Create an Eclipse Web Project
References
Servlets Tutorial
Tomcat Servlet Examples Explained
HTTP Methods Get vs Post
Using WebServlet Annotation in Tomcat

JSPs

JavaServer Pages (JSPs) are another component of a Web Application.

JavaServer Pages:

    • Mix HTML with Java Code by using scriplets <% some code %>
    • Allow dynamic content such as database content
    • Are translated in Java code
      • Static code is translated as prints to the output
      • Dynamic code is translated as Java code
    • The code is compiled into Servlets
    • When a reference is made to a JSP the servlet is run

An example of a JavaServer Page is given below.

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
  This is the testing page.
  <% int a, b;
     a = 5;
     b = a + 6;
  %>
  <br/>
  The integer was <%=b%>
</body>
</html>

Selenium IDE

  • Selenium IDE works from a simplistic programming language - Selenese
  • In the IDE you can specify Selenese commands
  • With the IDE you can record a session using the Firefox browser
The recording is in Selense, you can then
Run the test case
Modify the recording into the test case
Save the test case as Java
  • The IDE is useful for:
Prototyping
Getting a quick first pass at a test
Trying a prototype and then exporting to WebDriver Java Bindings

Selenese Primer

Record a test case

  • Go to a website that will be the starting point for recording
  • Turn on Recording by clicking the red button at the top right
  • Record a few actions
  • Stop and start recording whenever you want to
  • Build a prototype using some recording and some manual insertion of commands

Recording a Test Case Documentation

Build a test case

  • Open the Selenium IDE
  • First open a Firefox Browser
  • The IDE is an Add-on to the Firefox browser
Install the Add-on if it is not already present
This will give a "Selenium IDE menu item under tools in Firefox
  • Click on the Selenium IDE menu item to open the IDE
  • Commands can be added into the test one at a time
In the command window

Hands on Exercise

  • Open a Firefox browser
  • Open the Selenium IDE (from the Firefox browser)
  • Get the Selenium IDE Testcases Zip File
See the Section at the end of this document called Selenium Sample Zip Files
There is a link to the zip file in that section
  • Extract the Selenium Testcases folder into a well known location
  • In the Selenium IDE open the test called testcase2.html
  • Run this test case and watch the effect in the browser
  • Change the test case so that a different search term is put into Google
  • Run the test and watch the failure
  • Fix the test by choosing a different set of links to go to
Note that you can try getting new links by recording or manually
References
Selenium IDE Documentation
Selenium IDE Command Reference
Using Special Keys Like alt

Selenium Scheduler

  • The scheduler came out in version 2.9 of Selenium IDE
  • Click the scheduler button next to the record button in the upper right
    • Set up the time and test suite to schedule

References Selenium Scheduler

Reporting with Selenium IDE

  • There are a couple of Firefox plugins that help with reporting in the IDE
  • They are not as robust as the tools in Selenium WebDriver
References
Pretty Report Plugin
Test Results Plugin

HTML Tags

  • The easiest way to learn/use HTML is to use online references
There are a couple of the best ones in the references below
  • HTML is a markup language
  • XHTML is XML compliant

Hands on Exercise

  • Build a static HTML page in Eclipse in Web_Project_1
  • Add the following to your page
    • Some text from an article you look up on Wikipedia
    • An image from one of the search engines
      • Add the image to the Web_Project_1 images folder
    • An iframe using a YouTube video
    • Several links
    • Some div tags
    • A horizontal rule
    • A form should be at the top of the page with
      • textboxes
      • checkboxes
      • radio buttons
      • a select box
      • submit button
References
W3Schools on HTML Tags
TutorialsPoint Tutorial on HTML

XPath Navigation Primer

  • XPath is used to navigate through elements in a XML document
  • HTML is a subset of XML when properly formated
  • XPath can be used to navigate through elements in an HTML document
  • XPath is used in Selenium as element locators

XPath Primer

Cascading Style Sheets

  • Cascading Style Sheet selectors can be to locate elements
This is similar to using XPath locators
  • In CSS the following symbols are used:
. - this refers to a tag's class attribute
# - this refers to an tag's id attribute
  • Note that CSS may not work at times because the attributes will not give a unique element
For example classes may be used multiple times in a page on various tags
  • Note that in using CSS only the selectors are being used
  • General form of the selector:
css=<HTML tag><.or #><value of class or id attribute>

Example
css=input#Password[type='password'][name='Passwd']
css=#reauthEmail
References
Using CSS selectors as element locators
CSS and XPath Cheat Sheet
W3Schools CSS Tutorial

Selenium WebDriver

  • A browser WebDriver has a set of Programming Bindings
  • These bindings allow a program to automate the Browser
  • For example the following Java code opens a Firefox browser, gets Yahoo's main page, and finds an element in that page
browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo!" in browser.title
elem = browser.find_element_by_name("p") # Find the query box
driver.quit() # Close the browser window 
  • There are Selenium bindings in several programming languages
  • Java is one language for which bindings exist
  • These allow a Java program to control a browser
  • The browser can be instructed to;
  • Open
  • Request web pages from sites
  • Close
  • Once a page is retrieved it can have:
  • Its elements analyzed
  • Its inputs filled with data (i.e. HTML form inputs)
  • For example a search box or a username and password filled in
  • The form can be submitted
References
Selenium Documentation
WebDriver API by Example
Using JUnit Assert Statements
Selenium JavaDocs

WebDriver Installation and Configuration

The following sections describe the steps to be WebDriver installed they include:

  • Install the Java JDK
  • Install the Eclipse IDE (Integrated Development Environment)
  • Download Selenium Java Bindings Package for WebDriver
  • Configure Eclipse to use WebDriver libaries in a project

Install Java JDK

Note: This step was accomplished in prior sections it is here for reference

  • Go to the oracle.com Java downloads page referenced below and download the latest version of the Java JDK
Presently this is version 8u66 (make sure that you get the JDK
For Windows get the 64 (x64) or 32(x86) bit version depending upon your type of system
Is your computer a 64 bit or 32 bit computer?
Windows see Windows running 64 or 32 bit?
Mac see Mac OS X running 64 or 32 bit?
  • Install Java using the installer for your operating system type (Windows, Mac OS X)
  • Put the Java folder into your environment's path variable
Make sure you do not delete your path by mistake, it is hard to get it back
Hands on Exercise - Install Java JDK:
Using the following document install the Java JDK that corresponds to the type of Operating system that exists on your computer (Windows, Mac OS, Linux x64, etc.). The installation steps will be approximately the same for each operating system.
Installing the JDK
Reference

Oracle Java SE Downloads

Install Eclipse

Note: This step was accomplished in prior sections it is here for reference

  • Go to the Eclipse.org download page and get the latest version of Eclipse (see link below in References)
  • Extract the zip file into a folder in a well known location
  • Create a workspace folder in a well known location
    • Usually it is best to create a folder and place both Eclipse and the workspace in that folder
    • So that they are together
  • Create a shortcut to the eclipse.exe file on the desktop (at least for Windows)
Hands on Exercise - Install Eclipse:
Using the following instructions install Eclipse on your computer. Eclipse is an Integrated Development Environment commonly used by developers. Installation steps will be approximately the same for all operating systems. There is only one installation zip file for all operating systems.
Installing Eclipse
Reference

Eclipse Download Page

Download the Selenium WebDriver Bindings for Java

  • Go to the Selenium WebDriver download page and get the Java Bindings
    • You will also want to bookmark the Javadocs page
  • Unzip the bindings folder i.e. selenium-2.46.0 into a well known location
    • They will be imported (for lack of a better word) into your Eclipse Selenium project
References

Selenium Downloads Page

Configure Eclipse IDE with WebDriver

  • Launch Eclipse and choose the workspace folder you created when asked for a workspace
  • Create a new Java Project
  • Go to the Project's "Java Build Path"
  • Add the Selenium WebDriver JAR files to the Libraries tab
    • Click on Add External Libraries
    • Add all jars inside and outside of the lib folder

Export a Selenium IDE Test to WebDriver

  • The IDE has an export menu item
    • Export Test Case As -- Java/JUnit/WebDriver
  • Then copy the file in File Manager
  • Paste into the package com.example.tests in Eclipse
    • The files are exported with the package name com.example.tests
      • This package name can be changed in the file to put them into other packages

Hands on Exercise

  • Create a new Selenium IDE testcase to test
        http://localhost:8080/Web_Project_1/formsDemo.jsp
  • Automate walking through
    • Filling in the First Name and Last Name
    • Check the check boxes for bike and car
    • Select from the drop down select box
    • Use the radio buttons
    • Check that the data in the various inputs is correct using assert statements
    • Click the submit button
    • Check the data on the action page for correctness
      • Use verify statements
  • Export the IDE test case using a Java/JUnit/WebDriver export
  • Copy and Paste the resulting file into Eclipse in the proper package
  • Fix any errors in Eclipse
  • Run the JUnit test cases and understand them

Selenium JavaScript Primer

  • Integrated with Java, same syntax
  • Complementary to Java
  • Integrated with HTML
  • Browsers contain a JavaScript engine

JavaScript Language Constructs

  • Primitive types Boolean, Number, String
  • Declaring Variables - var theVariable //they are case sensitive
  • Assignment - theVariable = 240;
  • Variable scope - local(function), global
  • operators - arithmetic (+ -), comparison (== != <), relational (|| &&)
  • Conditionals and looping - while, for, if, if else
  • Functions - function functionname(parameter-list){statements}
  • events - onclick
  • Objects
      <script type="text/javascript">
         // Define a function which will work as a method
         function addPrice(amount){
            this.price = amount; 
         }
         
         function book(title, author){
            this.title = title;
            this.author  = author;
            this.addPrice = addPrice; // Assign that method as property.
         }
      </script>
<html>
   <body>
   
      <script language="javascript" type="text/javascript">
         <!--
            document.write("Hello World!")
         //-->
      </script>
      
   </body>
</html>
  • Native Objects - Number, Boolean, String, Array, Date, Math, RegExp
  • Arrays - theArray[1] var fruits = new Array( "apple", "orange", "mango" );
  • String - length, charAt, concat, indexOf, replace, slice, split, substring, toUpperCase


References
W3Schools JavaScript Tutorial
TutorialsPoint JavaScript Tutorial
JavaScript Differences Between Browsers

Selenium Java Primer

  • Selenium WebDriver uses a set of programmatic bindings
  • These allow automation of various web browsers
Such as Firefox, Internet Explorer, Safari, Chrome, etc.
  • The bindings are written for several programming languages
Such as Phython, Java, Ruby, JavaScript, PHP, C#, etc.
  • To use Java the language must be understood
    • Which is the purpose of the following References from the web
    • Depending upon the programming skills of those in attendance go over
      • Classes
      • Packages
      • Methods
      • Constructors
      • Eclipse Debugging (walk through the code)
      • The public static void main method
      • Variables (Local and Class Instance)
      • Control statements if, if/else, while, for, switch
      • Standard Libraries
      • Arrays, linked lists, hashmaps
      • Inheritance
      • Method overloading
      • Selenium WebDriver Classes
      • JUnit Tests
      • Exporting Selenium IDE commands as Java
References
TutorialsPoint Java Tutorial
Jenkov Java Tutorial
Java Beginners Tutorial
Java Tutorial
Oracle Java Tutorials
Selenium JavaDocs