0% found this document useful (0 votes)
9 views51 pages

New Selenium Session Java

Selenium is an open-source automated testing framework for web applications, supporting various browsers through WebDriver. The document provides detailed instructions on setting up Selenium with Java, including installation, environment variable configuration, and sample code for browser automation tasks. It also introduces TestNG as a testing framework that can be integrated with Selenium for managing testing requirements.

Uploaded by

Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views51 pages

New Selenium Session Java

Selenium is an open-source automated testing framework for web applications, supporting various browsers through WebDriver. The document provides detailed instructions on setting up Selenium with Java, including installation, environment variable configuration, and sample code for browser automation tasks. It also introduces TestNG as a testing framework that can be integrated with Selenium for managing testing requirements.

Uploaded by

Kumar
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Selenium Session

Using Java
What is Selenium?
SELENIUM is a free (open-source) automated testing framework used to validate
web applications across different browsers and platforms.

Official Website
[Link]

Download Link
[Link]
Selenium Webdriver
WebDriver drives a browser natively, as a user would, either locally or on a remote
machine using the Selenium server, marks a leap forward in terms of browser
automation.

Browsers supported by Selenium [Download]

● ChromeDriver - Chrome Browser


● GeckoDriver - Mozilla Browser
● IE driver
● SafariDriver
● OperaDriver
Selenium Installation
Requirements -

● Java Setup

● Selenium setup

● Selenium standalone server

● Other Jar files

● Driver exe
Java Setup

[Link]

Selenium setup

● Right-click on a created project and go down in the list and select


properties
● Select Java Build path -> libraries -> Add jar file
● Select Selenium-server -standalone -> open -> apply and close
● Complete jar file in downloads -> selenium -> copy gecko, chrome,IE driver
● Go to -> C:\Program Files -> paste there
● Jar Files - [Link]
Setting JAVA Path in Windows 10
● Goto environment variable setting(View advanced system settings)
● Click on option Environment variables
● Now set the JAVA_HOME Environment variable
● Now copy your java path: which is by default >> “C:\Program
Files\Java\<jdk-14.0.1>”, with the currently installed jdk version.
● Now, create new in “system variables” option and save as shown(named
JAVA_HOME)
Setting JAVA Path in Windows 10 - (continued)
● Now add the system variable to the path, scroll down and find path option.
● Goto path >> edit, then you’ll see a list of environment variable
● Now click new and added your recently created variable, (JAVA_HOME) with
it’s bin path
● Type in %JAVA_HOME%\bin >> click OK and it’s done
● Check it with cmd/powershell window
● Type java -version
Mac OS X: Installing Eclipse
Download the latest version of Eclipse from here

Eclipse IDE for Java Developers

All downloads are provided under the terms and conditions of the Eclipse
Foundation Software User Agreement unless otherwise specified.

Download Link

Download with file extension .dmg


Setting PATH of JAVA in Mac OS X
● After installing jdk(), open terminal
● Find out the location of java_home using the following command in the
terminal
● $ /usr/libexec/java_home -v14
● Path would be like
</Library/Java/JavaVirtualMachines/[Link]/Contents/Home> with current
jdk version - copy the path
● Then open this specific file in text editor using command
$ open ~/.bash_profile
sudo ln -s $(/usr/libexec/java_home)/lib/server/[Link] /usr/local/lib
Setting PATH of JAVA in Mac OS X - continued
● Now add one line in the end of file(PASTE THE COPIED PATH)
export JAVA_HOME =Library/Java/JavaVirtualMachines/[Link]/Contents/Home
● Or, use the path - then save the file
export JAVA_HOME=$(/usr/libexec/java_home)
● Open a Terminal and run the source command to apply the changes
$ source ~/.bash_profile
● Now check the value of the environment variable
$ echo $JAVA_HOME
● Check java version in terminal
$ java -version
WebDriver using Chrome Driver
package seleniumPrograms;

import [Link];

public class ChromeBrowserProgram {

public static void main(String[] args) {

// TODO Auto-generated method stub

[Link]("[Link]", "C:\\ProgramFiles\\[Link]");

ChromeDriver driver = new ChromeDriver();

[Link]("[Link]

}
WebDriver using FireFox Driver
package seleniumPrograms;

import [Link];

public class ChromeBrowserProgram {

public static void main(String[] args) {

// TODO Auto-generated method stub

[Link]("[Link]", "C:\\ProgramFiles\\[Link]");

FirefoxDriver driver = new FirefoxDriver();

[Link]("[Link]

}
Browser Automation
● Open a Webpage
● Locate Web Elements
● Navigating Web Pages
● Populate an Online Form
● Selenium WebDriver Waits
● Switch between IFrames
● Handle Alerts
● Switch Between Windows
Open a Webpage

package selenium_package_2;
import [Link];
import [Link];
import [Link];

public class OpeningWebpage{


public static void main(String[] args) {
// TODO Auto-generated method stub
[Link]("[Link]", "C:\\Program Files\\[Link]");
// open browser
WebDriver driver = new FirefoxDriver();
// pass url
[Link]("[Link]
[Link]();
}
}
Basics with Selenium Webdriver
Opening and Closing a website using Chrome Webdriver code

Opening and Closing a website using FireFox Webdriver code

Performing Simple Login by passing username and password to a demo site

Using Chrome Webdriver code, Using FireFox Webdriver code


Populating Form Entries
Filling up an online form(Live Example)

● Inputting the text entries, (Like: name, email, and comments)


● Clicking Radio-button options
● Clicking Check-button options
● Selection from dropdown menu(using visible text)

Code using ChromeDriver, Code using FirefoxDriver


Registration with Selenium WebDriver

public class Registration {


public static void main(String[] args) throws InterruptedException {
[Link]("[Link]", "C:\\Program
Files\\drivers\\[Link]");
ChromeDriver driver = new ChromeDriver();
[Link]("[Link]
[Link](3000);
[Link]([Link]("FirstName")).sendKeys("Mack");
[Link]([Link]("LastName")).sendKeys("Rae");
[Link]([Link]("Email")).sendKeys("boney@[Link]");
[Link]([Link]("CreatePassword")).sendKeys("12345");
[Link]([Link]("//input[@class='button']")).click();
[Link](2000);
}
}
Add registration code selenium
[Link]
public class Registration1 {

public static void main(String[] args) throws InterruptedException {

// TODO Auto-generated method stub

[Link]("[Link]", "C:\\Program Files\\drivers\\[Link]");

ChromeDriver driver = new ChromeDriver();

[Link]("[Link]

// [Link]().to("[Link]

// [Link]().back();
Locate Web Elements - using Firefox webdriver
Various Ways to Locate a Web Element.

Code
Locate Web Elements - using Chrome webdriver
package selenium_package_2;
import [Link];
import [Link];
import [Link];

public class LocateWebElements{


public static void main(String[] args) throws InterruptedException {
[Link]("[Link]", "C:\\Program Files\\[Link]");
WebDriver driver = new ChromeDriver();
// pass url
[Link]("[Link]
//Locating Web Element for input box "Enter Message"
//using ID
[Link]([Link]("email")).sendKeys("ID...");
[Link](1500);
//using NAME
[Link]([Link]("email")).sendKeys(" NAME...");
//using XPATH
[Link]([Link]("//input[@id='email']")).sendKeys(" Xpath...");
}
}
Navigating Web Pages
package selenium_package_2;
import [Link];
import [Link];
import [Link];

public class NavigateWebPages{


public static void main(String[] args) throws InterruptedException {
[Link]("[Link]", "C:\\Program Files\\[Link]");
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]("this is " + [Link]() + " website");
[Link]("url is: " + [Link]());
// navigating to another site
[Link]().to("[Link]
[Link]("this is " + [Link]() + " website");
[Link]("url is: " + [Link]());
// navigating back to google .com
[Link]().back();
[Link]("this is " + [Link]() + " website");
[Link]("url is: " + [Link]());
}
}
How to Handle Alerts - Example 1
import [Link];
import [Link];
import [Link];
import [Link];

public class _8ManagingAlerts {


public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
[Link]("[Link]", "C:\\Program Files\\[Link]");
// open browser
WebDriver driver = new FirefoxDriver();
// pass url
[Link]("[Link]
[Link]([Link]("proceed")).click();
Alert alert = [Link]().alert();
[Link](3000);
[Link]([Link]());
[Link]();
[Link]("a");
}
}
How to Handle Alerts - Example 2
Import all the dependencies

public class _9ManagingAlerts_Example2 {


public static void main(String[] args) throws InterruptedException {
[Link]("[Link]", "C:\\Program Files\\[Link]");
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link]([Link]("alert")).click();
Alert alert = [Link]().alert();
[Link]([Link]());
[Link](3000);
[Link]();
[Link]([Link]("confirm")).click();
Alert alert1 = [Link]().alert();
[Link]([Link]());
[Link](3000);
[Link]();
[Link]([Link]("prompt")).click();
Alert alert2 = [Link]().alert();
[Link]([Link]());
[Link](3000);
[Link]("hello");
[Link]();
}}
Read Any Web Attribute
package demo;

//import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class _7Read_attribute {


public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
[Link]("[Link]", "E:\\Selenium\\firefox\\[Link]");
// open browser
WebDriver driver = new FirefoxDriver();
// pass url
[Link]("[Link]
WebElement getcss = [Link]([Link]("dropdownCurrency"));
[Link]([Link]("font-family"));
[Link]([Link]("font-weight"));

[Link]();

}
}
Actions - Right Click on web element
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class _11RightClick {


public static void main(String[] args) {
// TODO Auto-generated method stub
[Link]("[Link]", "C:\\Program Files\\[Link]");
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
Actions action = new Actions(driver);
By locator = [Link]("//span[@class='context-menu-one btn btn-neutral']");
WebDriverWait wait = new WebDriverWait(driver, 5);
[Link]([Link](locator));
WebElement rightClickElement = [Link](locator);
[Link](rightClickElement).build().perform();
}

Creating object actions from class Actions


Actions - MouseOver event on web element
package demo;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class mouseover {


public static void main(String[] args) throws InterruptedException {
[Link]("[Link]", "E:\\Selenium\\firefox\\[Link]");
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
[Link](3000);
WebElement element = [Link]([Link]("//span[contains(text(),'Hello, Sign in')]")) ;
Actions action = new Actions(driver);
[Link]("Mouse is over the - HELLO, SIGN IN - option");
[Link](element).build().perform();
[Link](3000);
[Link]([Link]("//span[contains(text(),'Create a Wish List')]")).click();
[Link]("Clicked");

}
Actions - Drag-N-Drop event on web element
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class DragNdrop {


public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
[Link]("[Link]", "C:\\Program Files\\[Link]");
WebDriver driver = new FirefoxDriver();
[Link]("[Link]
// focussing inside the iframe
[Link]().frame(0);
//using xpath
WebElement source = [Link]([Link]("//div[@id='draggable']"));
WebElement target = [Link]([Link]("//div[@id='droppable']"));
//message for console - checking execution flow of program
[Link]("opening page...perform drag and drop");
[Link](3000);
Actions act =new Actions(driver);
[Link](source, target).build().perform();
[Link]("drag N drop Done...");
}

}
Getting Started with TestNG
What is TestNG?
TestNG is a testing framework for Java programming language. It can be
integrated with selenium framework to write test scripts.

Furthermore, it is designed to manage all testing requirements such as,

● functional testing
● regression
● end-to-end testing, and more.
Install TestNG in Eclipse
Please follow the instructions

Step by Step Instructions

Instead of old url

Please Use: [Link]

At last, please add TestNG library to eclipse project.


Create TestNG Class
● Goto your project >> New >> TestNG >> Create TestNG Class
● Name the Class (without selecting main() function)
● It will be created with annotations “@Test”
● Now, we can write our test case inside the method with @Test annotation.
● Let’s now test our code with simple print method of JAVA
● Run as >> TestNG Test

Example Code
TestNG Annotation
@BeforeSuite: The annotated method will be run before all tests in this suite have run.

@AfterSuite: The annotated method will be run after all tests in this suite have run.

@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the <test> tag is run.

@AfterTest: The annotated method will be run after all the test methods belonging to the classes inside the <test> tag have run.

@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.

@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.

@BeforeClass: The annotated method will be run before the first test method in the current class is invoked.

@AfterClass: The annotated method will be run after all the test methods in the current class have been run.

@BeforeMethod: The annotated method will be run before each test method.

@AfterMethod: The annotated method will be run after each test method.
TestNG Annotation
Here is a code for you to understand the order of all @Before & @After
annotations.

This code shows you the proper order of all the annotations.

Example Code
Running TestNG Test Cases
You can run TestNG cases using:

1. Direct run as testNG Test


2. Using the xml file - TestNG Suite
[Right click on the java file of test case >> TestNG >> Convert to TestNG]
Goto [Link] created outside in folder “test-output/test”
In the xml file, Run as >> TestNG Suite
3. Skip Test (Just remove group’s name from the include section)

Example format for xml file


TestNG Groups
TestNG allows you to separate different test cases into different groups and call
them inclusively by using the xml file.

This gives you flexible solution for you to partition your tests. Also,it allows you to
run two different sets of tests back to back.

In this example, we are going to show you how can use the TestNG groups
Login group contains open website, entering data and press login button
Explore group will responsible for exploring the home page.

Example Code
Test-case Priority
TestNG provides the option of setting priority. It can be used by providing simple
indexing(0,1,2,3...)

Example:
Priority 0 = import web browser settings
Priority 1 = opening web page
Priority 2 = performing login
Priority 3 = explore site

Example code
Dependencies with annotations in TestNG
You can use dependencies option to set the order of the test execution.

You have to put [dependsOnMethods = "<name of the method>"] on to the current


@test Method.

Example: login test >> dependson username, enterPassword>> click on Login

Example Code
@DataProviders in TestNG
A Data Provider is a method, using which returns an array of array of objects.

The method is annotated with @DataProvider

In this code, we are going to perform 3 login attempts(2 wrong credentials, 1 right)
and get the results. And, going to pass all the data(set of 3) by dataProvider.

Note: please do not name your class “DataProvider”

Example Code
TestNG Assertions
TestNG Assertion is a method to verify or to check the expected result and the
actual result are a match or not.

In this example we are going to learn how to use TestNG Assertions. We’ll be
using
assertTrue
assertFalse
assertEquals
assertNotEquals
assertNull
assertNotNull
assertSame
assertNotSame

Example Code
Disable in TestNG
TestNG @Test enable parameter is used for disabling a certain test case.

@Test(enabled = false)
public void your_method(){
<set of instruction>
}

This code will simply ignore the test method.


Another way of ignoring method is to give them certain group name and exclude
them while calling from xml file(Test Suit).

Example Code, XML File


Timeout in Methods
The timeOut is a attribute in TestNG, provides time duration for the execution of
the test method.

A timeOut time is set in milliseconds, after which the test method will be Failed.

Let’s try to understand this by using an example.

Example Code
Multiple Cross Browser Testing
Code
Cucumber with Selenium
Java (BDD Testing)
What is Cucumber
Cucumber is a software tool, and it supports BDD(behavior-driven development).

Cucumber BDD tool is very popular in testing industry, mainly because of the
writing test cases in (High Level)plain ordinary language called Gherkin. It's like
writing test cases in “english language”

It uses the framework annotations to understand software behaviors to be


specified in a logical language which is intelligible to the users.(Specially from
non-coding background)
BDD Approach
“The behavior-driven development” (BDD) is:
an Agile software development process
which inspires a joint effort among developers, QA and non-technical or
business participants in the project.

Framework approach in automation. A framework for test automation, consist of


different modules and libraries.

They simply use the object-oriented approach, to provide us with an integrated


system or environment, where we can write our test case for the specific product.
Cucumber Installation
Here is a guide from where you can follow step by step instruction to integrate
Cucumber framework into your Eclipse IDE

Step-by-Step Instruction

Cucumber Dependencies

Download Jar Files


Gherkin syntax
Gherkin is a line-oriented language that uses indentation to define structure, with
line ending termination.(Also called Steps)

Feature: feature login feature of new website for testing

Scenario: login test for new website

Given I am on the demo website "[Link]

When I type login = "a" and password = "a"

And I click sign-in button

Then I should get "SIGN-OFF" link


Feature File - Gherkin Language
Create a file with extension feature - “[Link]”

Feature: test scenario to test google search page


Scenario: Search with different set of words
Given I am on google page "[Link]
When I type login = "<seachWords>"
And I click on google search button

Goto run as >> run [Link] file


Step Definition File
A step definition is java file responsible for actually working on the feature file. It
can be a Regular Expression or a Cucumber Expression.

The examples in this section use Cucumber Expressions.

Example Code
TestRunner File
A test runner file is responsible for running the JUnit test on your step definition file
including feature file.

Run as >> JUnit Tests

Example Code
Cucumber Combined Practicals Links
Basic Program

[Link]
sp=sharing

Login Program

[Link]
sp=sharing

Scenario Based Login

[Link]
p=sharing

You might also like