Sie sind auf Seite 1von 17

introduction to selenium

selenium is a free open source software testing suite created in


2004 by jason huggins
selenium itself is not a single its is a combinition of several
tools

selenium have 3 versions


1.selenium ide(Selenium Integrated Development Environment)
2.selenium rc
3.selenium webdriver
4.selenium grid

Abstract methods are methods without structures but with only name
of the method

Ex:normal method

Public void non abstract (){

System.out.println(“this is normal method")

Abstract method EX:

Public abstract method;

Webdriver is a interface which has all the abstract methods

present of child classes like


Remote webdriver chromedriver,firefoxdriver,iedriver

So we can use webdriver object to instantiate any drivers like


chrome or firefox Hence

Webdriver driver= new chromedriver

Here webdriver is interface, driver is reference variable,new is


keyword which used to create object,and chrome driver is class

basic methods of webdriver

1.get();-it is used to load webpage


2.gettitle();-it is used to get the title of the desired webpage
3.getcurrenturl();-to get the current url of the webpage
4.getpagesource();-tget the source of last loaded page
5.quit();-to close every associated window
6.close to close current window

selenium locaters are used to find webelements in effective way by


using html code
1.id ex:driver.Findelement(by.id("demo")).sendkeys("demo1");
2.name
3.class name
4.linked text
5.xpath syntax://tagname[@attribute='value']

Select current node.


▪ Tagname: Tagname of the particular node.
▪ @: Select attribute.
▪ Attribute: Attribute name of the node.
▪ Value: Value of the attribute

6.css syntax://tagname[attribute*='value'] or
tagname#id or tagname.classname

traversing from parent to child in xpath syntax-


//tagname[@attribute='value']/child tagname

xpath types
relative xpath-does not depends on parent nodes
absolute xpath-finding xpath by using parent to child node

traversing from parent to child in xpath syntax-


//tagname[@attribute='value']/child tagname

traversing from child to parent in xpath


syntax-//tagnaname[@attribute='value']/parent::parenttagname

traversing from one node to sibling node in


xpath-//tagname[@attribute='value']/following-sibling::sibling
tagname

Contains()
Is another method in xpath with is ysed when when values of
attributes changing dynamically it will find attributes by using
partial text

Syntax tagname[contains,(@attribute,’partialtextvalue')]

Another one is contains with text which is used to find element by


its text

Syntax
Tagname[@contains(text(),’textvalue of attribute')]

Using or in xpath
Syntax
Tagname[@attribute=’value' or secattribute=’value']

Using and in xpath


Syntax
Tagname[@attribute=’value' and @scattribute=’value']

We can also find elements by using text without need of attributes


present in elements

Syntax

Tagname[text()=’textofelement’]

automation ui control concepts

dropdowns
1.static dropdown-static dropdown is which the options are
preloaded
dropdowns are clicked by using select class in java by creating
object

Select s=new select(locater of dropdown)


s.selectbyvalue()
S.selectbyindex()
Ssselectbyvisibletext()

2.dynamic dropdown-these are the dropdowns which have same


components on both dropdowns to solve that when we writing xpath
to that dropdown make sure
to tell the driver to click on second instance

checkboxes these are generally automated through locater


techniques
but to check wheather pirticular checkbox is checked we use an
importent class called "is selected();" class
there is another methods called "IS enabled()" and "IS disabled()"
this methods are used to check wheather the object is in anebled
mode or in disabled mode

java alerts

to handle java alerts we have function in webdriver called


"driver.switchto.alert"
we can click on ok button or to cancel we use dismiss or get text
from alert

radiobuttens
this are also webelements that are clicked by using locaters
techniques but if we need to click on radio butten which have same
attribute first we find count of that radio buttens by using
driver.findelements.size() keyword which count the total number
then we take them into list nd with the help of for and if loop we
click on that button

WAITS IN WEBDRIVER
Thread.sleep Command
▪ The sleep code always has to wait for the seconds mentioned
within the bracket, even if the work page is
ready after 5 seconds. So this test can slow down.
▪ Ex: Thread.sleep(5000); // Wait 5 Seconds
▪ Implicit Wait:
▪ Implicit Wait means informing selenium web driver to wait for
specific amount of time.
▪ If the web element is not visible after waiting for that
specific point then throw “NoSuchElementException”.
▪ Ex:
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);

Explicit Wait:
▪ In Explicit wait along with wait time we also provide the wait
condition for particular WebElement.
▪ It will wait till the condition or the maximum wait time
provided before throwing the Exception
“ElementNotVisibleException”.
▪ Wait for the WebDriver to check whether the element exists or to
operate on it, visible or enabled or disabled
or clickable.
▪ Ex:
// Create a Object wait of WebdriverWait class
WebDriverWait wait = new WebDriverWait(driver,30);
// Using ExpectedConditions wait until element visibility
wait.until(ExpectedConditions.visibilityOfElementLocatedBy.tagName
("input")));

some expected Wait conditions

elementToBeClickable:
– wait.until(ExpectedConditions.elementToBeClickable(element)); //
Wait until element to be clickable on
page
▪ elementToBeSelected:
– wait.until(ExpectedConditions.elementToBeSelected(element)); //
Wait until element to be selectable on page

invisibilityOf:
– wait.until(ExpectedConditions.invisibilityOf(element)); // Wait
and check element is invisibility
▪ presenceOfAllElementsLocatedBy:

wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy((By)
element)); // Wait until present element
located by.
▪ textToBePresentInElement:
– wait.until(ExpectedConditions.textToBePresentInElement(element,
"Text")); //// Wait until text present on
particular an element
▪ textToBePresentInElementValue:
– // Wait until element value present for a particular element.

wait.until(ExpectedConditions.textToBePresentInElementValue(elemen
t, "Value"));
▪ visibilityOf:
– // check element visibility
– wait.until(ExpectedConditions.visibilityOf(element));

ADVANCED WEB UI CONTROLS

ajax and mouse interactions-in this we use action class in


webdriver which is used to control movements of mouse
and also used in right clicking on an webelement by using "CONTEXT
CLICK" and it is also used in drag and drop or we can use this
class for double click
and to write words in capital letters in text field

Mouse Actions
– Mouse Hover
▪ moveToElement(WebElement).build().perform();
– Right Click
▪ contextClick(WebElement).build().perform();
– Double Click
▪ doubleClick(WebElement).build().perform();
– Drag and Drop
▪ dragAndDrop(Source WebElement, Target
WebElement).build().perform()
▪ clickAndHold(Source WebElement).moveToElement(Target
WebElement).release().build().perform();
– Slider
▪ moveToElement(WebElement).dragAndDropBy(WebElement, 300,
0).build().perform();
– Resizing
▪ moveToElement(WebElement).dragAndDropBy(WebElement, 100,
100).build().perform();

handling multipule windows-- to traverse from multiple windows use


the "driver.switchto.window pass parameter in window id"

we can get all windows id by using


method "driver.getwindow handle" with this we can get count of ids
and we take them to list and find unique window id

if we need to came to parent window we need to specify that id by


traversing into list

Set<string> ids = Driver.getwindowhandles()


Iterator<string> it=Ids.iterator()
Parent window=It.next()
Childid=it.next
To switch to child id we use
Driver.switchto.window(childid)

handling frames--- if the page having the tag name called iframe
or frame set then we decide that it is in frame

first we find how many frames are there in that


page by using "by.tagname.size()" which tells how many frames are
there
after that we use driver.switchto.frame method
to go into the desired frame
if we need to come to normal window from frame
we use "driver.switchto.defaultcontent"
in frames we can directly switch between frame
in frame where as in switching to seperate frame we need to come
back to normal window and switch to that frame

calender ui-- in calender ui we need to click on pirticular


calender and then we need to select the day which we needed
to set date we need one common attribute which have
same values by findelemednts method and take them into list by
using if and for loops we seek through
date and click on that

Auto suggestive dropdowns-to handle auto suggestable dropdowns


texts which are hidden selenium itself can't handle but by using
JAVA SCRIPT executer we can handle
by creating js object

JavascriptExecuter jj= (javascriptExecuter)driver

handling ssl and http certifications-- these are handeled through


by a class called desired capabilities by creating a object and
using chromeoptions class

Code for ssl certifications:

DesiredCapabilities ch=DesiredCapabilities.chrome();
//ch.acceptInsecureCerts();
ch.setCapability(CapabilityType.ACCEPT_INSECURE_CERTS, true);
ch.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);

//Belows to your local browser


ChromeOptions c= new ChromeOptions();
c.merge(ch);
System.setProperty("webdriver.chrome.driver", "");
WebDriver driver=new ChromeDriver(c);

we can tweak our browser


like maximize the window or delete cookies by using
"driver.manage" metho
we can also take screenshot
of the element by casting our driver to takescreenshot

(takescreenshot(driver)).getscreenshotas.(outputtypr.file)
default the file is saved
in src to copy the file from src to our required location we use
"fileutils." Class

File src=((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

FileUtils.copyFile(src,new File("C:\\Users\\rahul\\screenshot.png"));

fileutils is a class which is used to handle file functions and in


the same way there is a class called windows.util
which is used to manage
windows functions like killing process deleting cache etc

GRID

selenium grid is a tool which is used to run on different machines


aginst different browsers

in grid the local machine which controls the remote machines is


called hub and the remote machines are called as nodes

to run test cases on remote browser we need to give what browser


we willing to use and on which os

"Desiredcababilities" is class
which is used to tell the selenium which browser we need to use
and os

after giving the desired capabilities we need to create object for


remotewebdriver

WebDriver driver= new RemoteWebdriver(here we need to pass


argument which knows desiredcapabilities);

FRAMEWORK

TESTNG-it is a component in developing a framework the main use of


testng is to run multiple test cases in single class
it also helps in running multiple test classes at time and
control the test cases

importent concepts and classes in testng


1.testng xml- all our triggers and configurations of running test
cases are written in this xml file
for xml developing they created a structue
testsuite-test folder-test cases

test suite- it is the whole set of packages or modules or


collection of test folders
test folder-it is concidered as one module in test suite and
inside this module we have to write our test case configurations

the main use of xml is triggaring multiple testcases with single


click

include and exclude methods-these are methods which used in


controling the test cases
ex:if there are 10 test cases in a class and we need to skip a
pirticular test case then we use these include and exclude methods
<classes>
<class name=test.day3
<methods>
<include name="that method name"/> (in
testng every testcase is treated as test method)
<methods/>
<class/>
<classes/>
in the same if we need to exclude a method then

<classes>
<class name=test.day3/>
<methods>
<exclude name="that method name"/>
<methods/>
<class/>
<classes/>

*in testng framework every method has a unique keyword which


will help to run only certain testcases in that module

ex: if the there are 100 test cases in a whole carloan


module and we need to run a 50 testcases which are importent make
that test cases as smoke and use include to run only specific
tests
<classes>
<class name=test.day3
<methods>
<exclude name="smoke.*"/>
<methods/>
<class/>
<classes/>

in xml we can also run in whole package level by using a method

<package name="name of that package/>"


this method is used in between the test folder in xml

<suite name="personal loan">


<test name="car loan">
<packages>
<package name="pakage name need to include"/>
<packages/>
<suite/>
<test/>

testng annotations- BeforeSuite


BeforeTest
BeforeClass
BeforeMethod
AfterMethod
BeforeMethod
AfterMethod
AfterClass
AfterTest
AfterSuite

@BeforeSuite and @AfterSuite- in @BeforeSuite annotated method,


you can setup and start selenium drivers and
in @AfterSuite annotated method,
you can stop Selenium drivers

@BeforeClass and @AfterClass- In @BeforeClass annotated method,


you can setup your firefox properties, initialize your driver
and so on
in @AfterClass annotated method,
you can stop driver

@BeforeTest and @AfterTest-in @BeforTest method, you can set your


firefox profile preferences
in @AfterTest method, we generally use
for deleting cookies

@BeforeMethod and @AfterMe -in beforemethod the excution held


before every testmethod and in aftermethod excution willbe done
after every method

groups in testng
groups are exclusively useful when we need to work on smoke
testing

for every class we use unique key word to treat them as a groups

we use groups after @test. syntax is @test(groups={"group name"})

and in xml

if we need only smoke testcases then in between test and class we


add

<test>
<groups>
<run>
<include name="smoke/>"
</run>
</groups>
</test>

helper annotations

depends on is helper annotation which is used to when one method


is depending on another one

@Test(dependsonmethods={"method name that it depends"}

same way we can exclude a method or switch off that method by


using helper annotation @Test(enabled=false)

timeout is an another helper annotation which tells that wait for


pirticular time before throwing any error for that desired test
method

@Test(timeout=4000) by default timeout is in milli seconds

Today topic

testng listeners- listeners in the sense it listens the complete


testcase and when test is faild it goes to pirticular block and
excute that blockand continue listening the script if the script
it again goes to pirticular block and excute that block

When we talk about TestNG Listener we will use ITestListener


Interface.This interface has some methods which we need to
override as per our requirement.we need to implement the
ITestListener Interface and use those methods
note:first we need to make sure that we have given a listeners
path to xml

syntax:
<suite>
<listeners>
<listener class-name="package name.class name"/>
<listeners/>

<test>

the methods that we use in listeners interface is

@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub

@Override
public void onStart(ITestContext arg0) {
// TODO Auto-generated method stub

@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult
arg0) {
// TODO Auto-generated method stub

@Override
public void onTestFailure(ITestResult arg0) {

System.out.println("Screen shot
captured====="+arg0.toString());

@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub

@Override
public void onTestStart(ITestResult arg0) {
// TODO Auto-generated method stub
System.out.println("TestCase started===="
+arg0.toString());
}

@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub

to know the test case name or method name in listeners we use a


class called "Itestresult"

data driven
parameterization
in selenium we should not hard code the data like
username,password etc those are written in one properties file and
we use that prop file featured test cases

to read that properties file by using a class in java called


properties from java utils

"properties prop=new properties();" in this way we create a object


for properties class

and fileinputstream in java which is used for pointing where this


properties file is located we need to give path of the file as a
parameter in fileinputstream

"Fileinputstream fill=new Fileinputstream("path of the prop


file")"

we can also make reusable components if we need data driven for


many testcases

note: in java if we define driver object in loops the scope of


that driver lies in between that loop only if u
need it for whole test case we need to define in as a global so it
is applicable for whole test case

by using data driven parameterization we can make reusable global


methods so we can use that in whole project level or mubule level

note:inorder to inherete the properties of the reusable method we


have a concept in java called inheretance
and by using "extends" keyword

there are some cases which we need to drive data from excel sheet
and it is known as data driven from excel sheet

to drive data from excel first we follow a hierarchy


1)workbook
3)sheet
4)row
5)column
6)grab the value
to crate a class of a workbook we use "XSSF" keyword

note:getcelldata method is used to read the cell value with out


hardcoding and set cell data is used to set the value these are
methods available in "poi api"

MAVEN

it is a software project management and build management tool in


java frameworks developed by apache

maven has its own rpositary website "mvnrepositary.com" which all


the jars which required for the project is taken care

it also helps in maintaining common structure across organization


maven has templetes for most of the projects
wheather its testing or developing,api,appium etc

my-app
|-- pom.xml
`-- src
|-- main
| `-- java
| `-- com
| `-- mycompany
| `-- app
| `-- App.java
`-- test
`-- java
`-- com
`-- mycompany
`-- app
`-- AppTest.java

above is an empty structure created by bmaven in above structure


it devide all reusable methods,utilities into one package and
actual test cases into another packaage

note:in maven package name is knows as groud id and main project


name is artifact id and this artifact id and group id are used to
find project and and sub project uniquely and add jars
accordingly

pom.xml is main component in maven because it have all the


information about which jars needs to be downloaded

all the jars are added in pom.xml as dependencies


pom.xml always needs tobe in project level
archetype:generate is a keyword used to create a new maven project
using command promt

by default we cannot run our testcases only by adding dependancies


tothe pom.xml file

we need a plugin called surefireplugin to be able to run our


testcases in maven

if we need to run testcases through command prompt there are three


commands which will help us to triger the testcases

1)clean-generally it is used to clean the temparary files in a


project
2)compile-it is used to see wheather a build or test case has any
syntax errors
3)test-first it will clean the project after it compiles and then
after it finally triggers actual the testcases

note:to differentiate the testcases which have to run and reusable


classes we actually use "Test" at the end of each testcase name

another main feature of maven is that it can also triggers


testcases in testng xml file

we can also control which xml file to run if there are multiple
testng xml files by creating them as each profile

the command we use to run pirticular xml file is


"mvn test
-pxmlfilename"

jenkins

jenkins is an continous integration tool which will automate every


manual things

it even automate the triggaring of maven command that we need to


do manually in maven

the main feature of jenkins is scheduling of maven project i.e if


we need to trigger the testcases in daily bases every 2 am we can
do that with the help of jenkins

LOG4J api

log4j--it is a logging tool which helps us to maintain detailed


logs of our tastcases.
with log4j we can also save all our logs into a file and send that
file others

if we need introduce logs into class then need to implement


logmanager api and needs to create getlogger object in the
logmanager api

syntax for logmanager object is

private static logger log=logmanager.getlogger(here we need to


give exat path of the class name)

in log4j by default only errors have configurated to execute


however we can configure what to log by manually configurating xml
file

<?xml version="1.0" encoding="UTF-8"?>


<Configuration status="WARN"> Note: configuration file has
sections 1)appenders which helps in where to log and how to log
2)loggers which helps what to log
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level
%logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="error">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

log4j is also useful in maintainig logs in package level i.e we


can define what massages to excute in pirticular package

PAGE
OBJECT PATTERN MODEL

in framework, desinging is mainly based on by creating reusable


objects

in page object pattern we create reusable objects in page wise i.e


for home page we create one java class in that all the objects in
homepage are written in the
same way we create for all the pages in web application
we can create page object class by simply using constructer class
in java

public Homepage(here we write webdriver driver as an argument


because we wrote it as an argument in actual testcase)
homepage is class name here
{

to give testcase webdriver propeties to local driver we use "this"


keyword i.e this.driver=driver

in page object patern we can define objects in two methods

1)driver.fimdelements(by.xpath("****")) this is generic method

2)another one is by using page object factory this is more


simplified form of creating objects

in page object factory we use "@findby" annotation to locate the


webeleFindby

This is for element finding


@Findby(name=”value")
WebElement txtusernane;

This tells what action WebElement does


Public void getusername(string uname)
{
Txtusername.sendkeys(uname)

imp general questions

Coming in the morning and checking the nightly build result (If
you have any nightly build scheduled)
Work on the failures of the script you found during the nightly
builds.

Then you should check your Automation Report , whether Failed Test
cases are really failed i.e Whether Application functionality has
failed or script itself failed.

You need to check any new requirement has come, if so, you need to
modify your script.
Adding additional automation framework features and Writing &
testing more automation test scripts
we have daily,weekly meetings regarding to status

Das könnte Ihnen auch gefallen