Sie sind auf Seite 1von 12

Class Hierarchy

o java.lang.Object
o org.openqa.selenium.By
o org.openqa.selenium.By.ByClassName (implements java.io.Serializable)
o org.openqa.selenium.By.ByCssSelector (implements java.io.Serializable)
o org.openqa.selenium.By.ById (implements java.io.Serializable)
o org.openqa.selenium.By.ByLinkText (implements java.io.Serializable)
o org.openqa.selenium.By.ByName (implements java.io.Serializable)
o org.openqa.selenium.By.ByPartialLinkText (implements java.io.Serializable)
o org.openqa.selenium.By.ByTagName (implements java.io.Serializable)
o org.openqa.selenium.By.ByXPath (implements java.io.Serializable)
o org.openqa.selenium.Cookie (implements java.io.Serializable)
o org.openqa.selenium.Cookie.Builder
o org.openqa.selenium.DeviceRotation
o org.openqa.selenium.Dimension
o org.openqa.selenium.ImmutableCapabilities (implements java.io.Serializable)
o org.openqa.selenium.MutableCapabilities (implements java.io.Serializable)
o org.openqa.selenium.Point
o org.openqa.selenium.Proxy
o org.openqa.selenium.Rectangle
o java.lang.Throwable (implements java.io.Serializable)
o java.lang.Exception
o java.lang.RuntimeException
o org.openqa.selenium.WebDriverException
o org.openqa.selenium.ImeActivationFailedException
o org.openqa.selenium.ImeNotAvailableException
o org.openqa.selenium.InvalidArgumentException
o org.openqa.selenium.InvalidCookieDomainException
o org.openqa.selenium.InvalidElementStateException
o org.openqa.selenium.ElementNotInteractableException
o org.openqa.selenium.ElementClickInterceptedExce
ption
o org.openqa.selenium.ElementNotVisibleException
o org.openqa.selenium.ElementNotSelectableException
o org.openqa.selenium.JavascriptException
o org.openqa.selenium.NoSuchSessionException
o org.openqa.selenium.NotFoundException
o org.openqa.selenium.NoAlertPresentException
o org.openqa.selenium.NoSuchContextException
o org.openqa.selenium.NoSuchCookieException
o org.openqa.selenium.NoSuchElementException
o org.openqa.selenium.InvalidSelectorException
o org.openqa.selenium.NoSuchFrameException
o org.openqa.selenium.NoSuchWindowException
o org.openqa.selenium.ScriptTimeoutException
o org.openqa.selenium.SessionNotCreatedException
o org.openqa.selenium.StaleElementReferenceException
o org.openqa.selenium.TimeoutException
o org.openqa.selenium.UnableToSetCookieException
o org.openqa.selenium.UnhandledAlertException
o org.openqa.selenium.UnsupportedCommandException

Interface Hierarchy
o org.openqa.selenium.Alert
o org.openqa.selenium.Capabilities
o org.openqa.selenium.ContextAware
o org.openqa.selenium.HasCapabilities
o org.openqa.selenium.JavascriptExecutor
o org.openqa.selenium.OutputType<T>
o org.openqa.selenium.Rotatable
o org.openqa.selenium.SearchContext
o org.openqa.selenium.WebDriver
o org.openqa.selenium.WebElement (also extends org.openqa.selenium.TakesScreenshot)
o org.openqa.selenium.TakesScreenshot
o org.openqa.selenium.WebElement (also extends org.openqa.selenium.SearchContext)
o org.openqa.selenium.WebDriver.ImeHandler
o org.openqa.selenium.WebDriver.Navigation
o org.openqa.selenium.WebDriver.Options
o org.openqa.selenium.WebDriver.TargetLocator
o org.openqa.selenium.WebDriver.Timeouts
o org.openqa.selenium.WebDriver.Window

Annotation Type Hierarchy


o org.openqa.selenium.Beta (implements java.lang.annotation.Annotation)

Enum Hierarchy
o java.lang.Object
o java.lang.Enum<E> (implements java.lang.Comparable<T>, java.io.Serializable)
o org.openqa.selenium.Proxy.ProxyType
o org.openqa.selenium.ScreenOrientation
o org.openqa.selenium.Platform
o org.openqa.selenium.Architecture
o org.openqa.selenium.Keys (implements java.lang.CharSequence)
o org.openqa.selenium.PageLoadStrategy
o org.openqa.selenium.UnexpectedAlertBehaviour

Get data from dropdown:


1. WebElement mySelectElement = driver.findElement(By.id("mySelect"));
Select dropdown= new Select(mySelectElement);
dropdown.selectByVisibleText("Italy");
dropdown.selectByIndex(2);

2. WebElement ele=driver.findElement(By.xpath(".//*[@id='month']"));
List<WebElement> x = ele.findElements(By.tagName("option"));
for(WebElement ele1 : x) {
String y=ele1.getAttribute("innerHTML");
System.out.println(y);
}

Read Data from Excel:


FileInputStream ExcelFile = new FileInputStream(Path);
XSSFWorkbook ExcelWBook = new XSSFWorkbook(ExcelFile);
XSSFSheet ExcelWSheet = ExcelWBook.getSheet(SheetName);
XSSFCell Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);

Write Data in Excel:


FileInputStream ExcelFile = new FileInputStream(Path);
XSSFWorkbook ExcelWBook = new XSSFWorkbook(ExcelFile);
XSSFSheet ExcelWSheet = ExcelWBook.getSheet(SheetName);
XSSFRow Row = ExcelWSheet.getRow(RowNum);
XSSFCell Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
FileOutputStream fileOut = new FileOutputStream(Path);
ExcelWBook.write(fileOut);
fileOut.flush();
fileOut.close();
Read data from Web Grid:
WebElement ele= Driver.findElement(By.Xpath(“”));
List<WebElement> ele_list=ele.findElements(By.tagName(“”));
For(WebElement ele_itration : ele_list)
{
Ele_itration.getText();
}

Testng Annotation:
1. It gives the ability to produce HTML Reports of execution
2. Annotations made testers life easy
3. Test cases can be Grouped & Prioritized more easily
4. Parallel testing is possible
5. Generates Logs
6. Data Parameterization is possible

@BeforeSuite
@BeforeTest
@BeforeClass
@BeforeMethod
@Test
@AfterMethod
@BeforeMethod
@AfterMethod
@AfterClass
@AfterTest
@AfterSuite

Below are the lists of attributes that we can pass to our Test method:
alwaysRun: This is used when we want to make sure a method always runs even if the
parameters on which the method depends, fails. If set to true, this test method
will always run. Eg: @Test(alwaysRun = true)

dataProvider: TestNG dataProvider is used to provide any data for parameterization.


Eg. @Test(dataProvider = “Hello”).
dataProviderClass: This is the class from where we pass the data to data provider.
In our case dataProvider class name is “Hello”.

dependsOnGroups: It is the list of groups this method depends on. Eg: @Test (groups
= { “City” ,”State” })

dependsOnMethods: This command is used to execute a method based on its dependent


method. Eg: @Test (dependsOnMethods = { “OpenBrowser” ,”database is up” })

description: It is the description for the method. Eg: @Test(description = “test


method”)

invocationCount: It refers to the number of times a method should be invoked. It


will work as a loop. Eg: @Test(invocationCount = 7) . Hence, this method will
execute 7 times.

invocationTimeOut: This refers to the maximum number of milliseconds a method


should take for all the invocationCount to complete. This attribute will be ignored
if invocationCount is not specified. Eg: @Test(invocationCount =7,invocationTimeOut
= 30 )

priority: This command sets the priority of the test method. Lower priorities will
be scheduled first. Eg: @Test (priority =1)
Test Case Grouping:

public class Grouping { <suite name="Suite">


<test name="Practice Grouping">
@Test (groups = { "Car" }) <groups>
public void Car1() { <run>
System.out.println("Batch Car - Test car 1"); <include name="Car" />
} </run>
</groups>
@Test (groups = { "Car" }) <classes>
public void Car2() { <class name="automationFramework.Grouping" />
System.out.println("Batch Car - Test car 2"); </classes>
} </test>
</suite>
@Test (groups = { "Scooter" })
public void Scooter1() {
System.out.println("Batch Scooter - Test scooter 1");
}
@Test (groups = { "Car", "Sedan Car" })
public void Sedan1() {
System.out.println("Batch Sedan Car - Test sedan 1");
}
}

Dependent Test:

public class Dependent {

@Test (dependsOnMethods = { "OpenBrowser" })


public void SignIn() {
System.out.println("This will execute second (SignIn)");
}

@Test
public void OpenBrowser() {
System.out.println("This will execute first (Open Browser)");
}

@Test (dependsOnMethods = { "SignIn" })


public void LogOut() {
System.out.println("This will execute third (Log Out)");

}
}

Read data from database:


Connection con = DriverManager.getConnection(dbUrl,username,password);
Statement stmt = con.createStatement();
ResultSet rs= stmt.executeQuery(query);
while (rs.next()){
String myName = rs.getString(1);
String myAge = rs.getString(2);
}
con.close();

Write data in database:


Connection con = DriverManager.getConnection(dbUrl,username,password);
Statement stmt = con.createStatement();
st.executeUpdate("INSERT INTO Customers VALUES (1001, 'Simpson', 'Mr.',
'Springfield', 2001)");
con.close();
Multi Browser Testing using Selenium TestNG:
it is required to perform multi-browser testing to make sure that the functionality
is working as expected with every browser to give equal user experience to all of
the wide range of audience

public class MultiBrowser { <suite name="Suite"


parallel="none">
public WebDriver driver;
<test name="FirefoxTest">
@Parameters("browser")
@BeforeClass <parameter name="browser"
public void beforeTest(String browser) { value="firefox" />
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver(); <classes>
}else if (browser.equalsIgnoreCase("ie")) {
<class
System.setProperty("webdriver.ie.driver name="automationFramework.MultiBro
","D:\ToolsQA\OnlineStore\drivers\IEDri wser" />
verServer.exe");
driver = new InternetExplorerDriver(); </classes>
}
driver.get("http://www.store.demoqa.com"); </test>

} <test name="IETest">

@Test <parameter name="browser"


public void login() throws value="ie" />
InterruptedException {
<classes>
driver.findElement(By.xpath(".//*[@id='
account']/a")).click(); <class
name="automationFramework.MultiBro
driver.findElement(By.id("log")).sendKeys("te wser" />
stuser_1");
</classes>
driver.findElement(By.id("pwd")).sendKeys("Te
st@123"); </test>

driver.findElement(By.id("login")).click(); </suite>
}
@AfterClass public void afterTest() {
driver.quit();
}
}

Action Class:
Method Description
clickAndHold() Clicks (without releasing) at the current
mouse location.
contextClick() Performs a context-click at the current
mouse location.
doubleClick() Performs a double-click at the current mouse
location.
dragAndDrop(source, Performs click-and-hold at the location of
target) the source element, moves to the location of
the target element, then releases the mouse.
Parameters:
source- element to emulate button down at.
target- element to move to and release the
mouse at.
dragAndDropBy(source, x- Performs click-and-hold at the location of
offset, y-offset) the source element, moves by a given offset,
then releases the mouse.

Parameters:

source- element to emulate button down at.

xOffset- horizontal move offset.

yOffset- vertical move offset.


keyDown(modifier_key) Performs a modifier key press. Does not
release the modifier key - subsequent
interactions may assume it's kept pressed.

Parameters:

modifier_key - any of the modifier keys


(Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
keyUp(modifier _key) Performs a key release.

Parameters:

modifier_key - any of the modifier keys


(Keys.ALT, Keys.SHIFT, or Keys.CONTROL)
moveByOffset(x-offset, Moves the mouse from its current position
y-offset) (or 0,0) by the given offset.

Parameters:

x-offset- horizontal offset. A negative


value means moving the mouse left.

y-offset- vertical offset. A negative value


means moving the mouse down.
moveToElement(toElement) Moves the mouse to the middle of the
element.

Parameters:

toElement- element to move to.


release() Releases the depressed left mouse button at
the current mouse location
sendKeys(onElement, Sends a series of keystrokes onto the
charsequence) element.

Parameters:

onElement - element that will receive the


keystrokes, usually a text field

charsequence - any string value representing


the sequence of keystrokes to be sent

Actions builder = new Actions(driver);


Action mouseOverHome = builder.moveToElement(link_Home).build();
mouseOverHome.perform();
Drag and Drop:
1. Actions action = new Actions(driver);
action.dragAndDrop(sourceElement, destinationElement).build().perform();

2. Actions builder = new Actions(Driver.Browser.Instance);


IAction dragAndDrop = builder.ClickAndHold(fromElement)
.MoveByOffset(-1, -1)
.MoveToElement(toElement)
.Release(toElement)
.Build();
dragAndDrop.Perform();

Robot Class:

Robot robot = new Robot();


StringSelection username = new StringSelection("username");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(username, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

//tab to password entry field


rb.keyPress(KeyEvent.VK_TAB);
rb.keyRelease(KeyEvent.VK_TAB);
Thread.sleep(2000);

//Enter password by ctrl-v


StringSelection pwd = new StringSelection("password");
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(pwd, null);
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_V);
rb.keyRelease(KeyEvent.VK_CONTROL);

//press enter
rb.keyPress(KeyEvent.VK_ENTER);
rb.keyRelease(KeyEvent.VK_ENTER);

Difference between single / and double //:


Static / Absolute (/):

It is the direct way to find the element, but the disadvantage of the absolute
XPath is that if there are any changes made in the path of the element then that
XPath gets failed.
The key characteristic of XPath is that it begins with the single forward slash(/)
,which means you can select the element from the root node.

=> html/body/div[1]/section/div[1]/div/div/div/div[1]/div/div/div/div/div[3]/div[1]
/div/h4[1]/b

Dynamic / Relative (//) =>

For Relative Xpath the path starts from the middle of the HTML DOM structure. It
st`arts with the double forward slash (//), which means it can search the element
anywhere at the webpage.
You can start from the middle of the HTML DOM structure and no need to write long
xpath.

//*[@class='featured-box']//*[text()='Testing']
Type of Xpath:
Contains():
Contains() is a method used in XPath expression. It is used when the value of any
attribute changes dynamically, for example, login information.

Xpath=//*[contains(@type,'sub')]

Using OR & AND:


In OR expression, two conditions are used, whether 1st condition OR 2nd condition
should be true. It is also applicable if any one condition is true or maybe both.
Means any one condition should be true to find the element.

Xpath=//*[@type='submit' OR @name='btnReset']

Start-with function:
Start-with function finds the element whose attribute value changes on refresh or
any operation on the webpage. In this expression, match the starting text of the
attribute is used to find the element whose attribute changes dynamically. You can
also find the element whose attribute value is static (not changes).

Xpath=//label[starts-with(@id,'message')]

Text():
In this expression, with text function, we find the element with exact text match
as shown below. In our case, we find the element with text "UserID".

Xpath=//td[text()='UserID']

XPath axes methods:


These XPath axes methods are used to find the complex or dynamic elements.

Following: Selects all elements in the document of the current node( )

Xpath=//*[@type='text']//following::input[1]

Ancestor: The ancestor axis selects all ancestors element (grandparent,


parent, etc.) of the current node as shown in the below screen.

Xpath=//*[text()='Enterprise Testing']//ancestor::div

Child : Selects all children elements of the current node (Java) as shown in
the below screen.

Xpath=//*[@id='java_technologies']/child::li

Preceding: Select all nodes that come before the current node

Xpath=//*[@type='submit']//preceding::input

Following-sibling: Select the following siblings of the context node.


Siblings are at the same level of the current node. It will find the element
after the current node.

xpath=//*[@type='submit']//following-sibling::input

Parent: Selects the parent of the current node

Xpath=//*[@id='rt-feature']//parent::div

Self: Selects the current node or 'self' means it indicates the node itself

Xpath =//*[@type='password']//self::input

Descendant: Selects the descendants of the current node

Xpath=//*[@id='rt-feature']//descendant::a[1]
Selenium Grid
Selenium Grid is a part of the Selenium Suite that specializes in running multiple tests
across different browsers, operating systems, and machines in parallel.

There are two main elements to Selenium Grid — a hub, and nodes.

Hub
the hub is a computer which is the central point where we can load our tests into. Hub
also acts as a server because of which it acts as a central point to control the network
of Test machines. The Selenium Grid has only one hub and it is the master of the network.
When a test with given DesiredCapabilities is given to Hub, the Hub searches for the node
witch matches the given configuration.

Node
a node is referred to a Test Machine which opts to connect with the Hub. This test
machine will be used by Hub to run tests on. A Grid network can have multiple nodes. A
node is supposed to have different platforms i.e. different operating system and
browsers. The node does not need the same platform for running as that of hub.

Install Selenium GRID:

Download Selenium Server jar file


http://www.seleniumhq.org/download/

Open the command prompt and navigate to a folder where the server is located. Run the
server by using below command

java -jar selenium-server-standalone-2.41.0.jar -role hub

The hub will use the port 4444 by default. This port can be changed by passing the
different port number in command prompt provided the port is open and has not been
assigned a task.

Go to the other machine where you intend to setup Nodes. Open the command prompt and run
the below line.

java -jar selenium-server-standalone-2.41.0.jar -role node -hub


http://localhost:4444/grid/register -port 5556

Run the selenium server in other machines to start nodes

For Instance, if you want to use only IE you can start the node by using below command

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore

Similarly for Firefox:

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556 -browser browserName=firefox

For Chrome:

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556 -browser browserName=chrome

There are few scenarios where you may need the browser from each type i.e.: IE, Chrome
and Firefox.

For instance, you may need to use 1 IE and 1 Firefox and 1 Chrome browser

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556 -browser browserName=iexplore
-browser browserName=firefox -browser browserName=chrom
maxInstance is used to limit the number of browser initialization in a node.
For example, if you want to work with 2 Firefox and 2 IE then you can start the node
using maxInstance.

java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub


http://localhost:4444/grid/register -port 5556 -browser browserName=firefox,maxInstance=3

Similarly, other browser instances can be configured using maxInstances.

maxSession

maxSession is used to configure how many numbers of browsers can be used parallel in the
remote system.
java -jar selenium-server-standalone-2.41.0.jar -role webdriver -hub
http://localhost:4444/grid/register -port 5556 -browser browserName=chrome,maxInstance=3
-browser browserName=firefox,maxInstance=3 –maxSession 3

Similarly, you can start multiple nodes and configuration can be verified in the console.
Here I have taken sample test to login to Gmail and enter username and password

public class GridExample {


@Test
public void mailTest() throws MalformedURLException{
DesiredCapabilities dr=null;
if(browserType.equals("firefox")){
dr=DesiredCapabilities.firefox();
dr.setBrowserName("firefox");
dr.setPlatform(Platform.WINDOWS);
}else{
dr=DesiredCapabilities.internetExplorer();
dr.setBrowserName("iexplore");
dr.setPlatform(Platform.WINDOWS);
}
RemoteWebDriver driver=new RemoteWebDriver(new
URL(http://localhost:4444/wd/hub), dr);
driver.navigate().to("http://gmail.com");
driver.findElement(By.xpath("//input[@id='Email']"))
.sendKeys("username");
driver.findElement(By.xpath("//input[@id='Passwd']"))
.sendKeys("password");
driver.close();
}

As in the example, you have to use RemoteWebDriver if you are using GRID and you have to
provide capabilities to the browser. You have to set the browser and platform as above.
In this example, I have used the platform as WINDOWS. You can use any platform as per
your requirement.
Version of browser can also be set by using dr.setVersion(“version”)
For Instance, you need to run this test serially in multiple browsers you have to
configure your testng.xml.Below is the testng.XML suite for above test to run your test
serially.

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


<suite name="GRID SAMPLE TEST" thread-count="2">
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER IE">
<parameter name ="browserType" value="IE"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>

<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER FF ">


<parameter name ="browserType" value="firefox"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
</suite>
To run the test parallel, you have to change your testng.xml like below.

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


<suite name="GRID SAMPLE TEST" parllel="tests" thread-count="3">
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER FF">
<parameter name ="browserType" value="firefox"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
<test name="GRID TEST WITH SERIAL EXECTION WITH BROWSER IE">
<parameter name ="browserType" value="IE"/>
<classes>
<class name ="GridExample"/>
</classes>
</test>
</suite>

Here in the testng.XML you have to specify the parameter as parllel=“tests” and thread-
count=“3” describes the maximum number of threads to be executed in parallel.
Framework:

CI Server .config/xml Generic Utilities Library Application Specific


(Jenkins) Files Library
(Data Driver, Web and mobile
acceleration) (IOS and Windows)

Repository

(GitHub) Launch
Launch
Script Automation Scripts
Script
Test
Management
Tool

(JIRA)
Reporting
Test Data Test
Object
(Excel, Controllers
(Excel, Management
emails,
Database (Elements
(POM) Database,
, .csv) Path)
Testng)

AUT

Das könnte Ihnen auch gefallen