Selenium Guide

33
SELENİUM GUİDE Selin Gungor

Transcript of Selenium Guide

Page 1: Selenium Guide

SELENİUM GUİDESelin Gungor

Page 2: Selenium Guide

WHAT İS AUTOMATİON TESTİNG?

Process of automating the

manual process to test the

SUT

Page 3: Selenium Guide

WHAT İS SELENİUM?

Selenium automate browsers.That’s it!

Page 4: Selenium Guide

WHY?• is open source and free• have a large user base and helping communities

• have cross Browser Compatibility(Firefox, chrome, Internet Explorer, Safari etc.)

• have great platform compatibility (Windows, Mac OS, Linux etc.)

• supports multiple programming languages (Java, C#, Ruby, Python, Pearl etc.)

• has fresh and regular repository developments• supports distributed testing

Page 5: Selenium Guide

UNFORTUNATELY.. Supports only web

based applications. No feature such as

Object Repository/Recovery Scenario

Cannot access controls within the browser.

No default test report generation.

For parameterization, users has to rely on the programming language.

Page 6: Selenium Guide

SELENİUM COMPONENTS?Tool Description

Selenium IDE Selenium Integrated Development Environment (IDE) is a Firefox plugin that lets testers to record their actions as they follow the workflow that they need to test. Record and playback tool! SIDE is a Javascript based framework.

Selenium RC Selenium Remote Control (RC) is a server that allows user to create test scripts in a desired programming language. It also allows executing test scripts within the large spectrum of browsers. It makes use of the full power of programming languages such as Java, C#, PHP, Python, Ruby and PERL to create more complex tests. SRC is a JavaScript based Framework

Selenium WebDriver WebDriver is a different tool altogether that has various advantages over Selenium RC. WebDriver directly communicates with the web browser and uses its native compatibility to automate.

Selenium Grid Selenium Grid is a tool used to run parallel tests across different machines and different browsers simultaneously which results in minimized execution time.

Page 7: Selenium Guide

WHO DEVELOPED SELENİUM? Since Selenium is a collection of different tools, it had different

developers as well. Below are the key persons who made notable contributions to the Selenium Project.

Primarily, Selenium was created by Jason Huggins in 2004 An engineer at ThoughtWorks, he was working on a web

application that required frequent testing. Having realized that the repetitious manual testing of their application was becoming more and more inefficient, he created a JavaScript program that would automatically control the browser's actions. He named this program as the "JavaScriptTestRunner."

Seeing potential in this idea to help automate other web applications, he made JavaScriptRunner open-source which was later re-named as Selenium Core.

Page 8: Selenium Guide

THE SAME ORIGIN POLICY ISSUE

First of all “Same Origin Policy” is introduced for security reason, and it ensures that content of your site will never be accessible by a script from another site. As per the policy, any code loaded within the browser can only operate within that website’s domain.

Same Origin policy prohibits JavaScript code from accessing elements from a domain that is different from where it was launched.

Example : The HTML code in www.google.com uses a JavaScript program

"randomScript.js". The same origin policy will only allow randomScript.js to access pages within google.com such as google.com/mail, google.com/login, or google.com/signup. However, it cannot access pages from different sites such as yahoo.com/search because they belong to different domains.

This is the reason why prior to Selenium RC, testers needed to install local copies of both Selenium Core (a JavaScript program) and the web server containing the web application being tested so they would belong to the same domain. 

Page 9: Selenium Guide

HAS FOUR COMPONENTS..

Page 10: Selenium Guide

BIRTH OF SELENIUM 2

In 2008, the whole Selenium Team decided to merge WebDriver and Selenium RC to form a more powerful tool  called Selenium 2, with WebDriver being the core.

Page 11: Selenium Guide

SO, WHY THE NAME SELENIUM? It came from a joke which Jason

cracked one time to his team. Another automated testing framework was popular during Selenium's development, and it was by the company called Mercury Interactive . Since Selenium is a well-known antidote for Mercury poisoning, Jason suggested that name. His teammates took it, and so that is how we got to call this framework up to the present.

Page 12: Selenium Guide

SELENIUM - IDE The Selenium-IDE

(Integrated Development Environment) is an easy-to-use Firefox plug-in to develop Selenium test cases.

It provides a Graphical User Interface for recording user actions using Firefox which is used to learn and use Selenium

It can only be used with Firefox browser as other browsers are not supported.

Page 13: Selenium Guide

 WHAT IS SELENESE?

Selenese is the language which is used to write test scripts in Selenium IDE.

EX:Selenium RC is slower than WebDriver as it doesn't communicates directly with the browser; rather it sends selenese commands over to Selenium Core which in turn communicates with the browser.

Page 14: Selenium Guide

SELENİUM WEBDRİVER

https://www.w3.org/TR/webdriver/

Page 15: Selenium Guide

• WebDriver’s goal is to supply a well-designed object-oriented API that provides improved support for modern advanced web-app testing problems.

SELENİUM WEBDRIVER • The primary new feature in

Selenium 2.0 is the integration of the WebDriver API.

• WebDriver is designed to provide a simpler, more concise programming interface in addition to addressing some limitations in the Selenium-RC API.

• Selenium-WebDriver was developed to better support dynamic web pages where elements of a page may change without the page itself being reloaded.

Page 16: Selenium Guide

SELENİUM 3.0 Minimum java version is now 8+ The original RC APIs are only available via the

leg-rc package. To run exported IDE tests, ensure that the leg-rc

package is on the classpath. Support for Firefox is via Mozilla’s geckodriver. You

may download this from Gecko Driver Release Support for Safari is provided on macOS (Sierra or

later) via Apple’s own safaridriver.* Support for Edge is provided by MS:MicrosoftWebDriver Download

Official support for IE requires version 9 or above. Earlier versions may work, but are no longer supported as MS has end-of-lifed them.Other major changes:* New html-table runner backed by WebDriver.* Unused command line arguments are now no longer parsed

Page 17: Selenium Guide

SELENİUM WEBDRİVER ARCHİTECTURE

•Multi-browser testing including improved functionality for browsers which is not well-supported by Selenium RC (Selenium 1.0).•Handling multiple frames, multiple browser windows, popups, and alerts.•Complex page navigation.•Advanced user navigation such as drag-and-drop.•AJAX-based UI elements.

Page 18: Selenium Guide

A COMMAND TELLS SELENIUM WHAT TO DO - ACTİONS

Command/Syntax Description

highlight (locator) Changes the background Color of the specified element to yellow Briefly which is useful for debugging purposes.

mouseDown (locator) Simulates a user pressing the left mouse button on the specified element.

mouseDownAt (locator,coordString)

Simulates a user pressing the left mouse button at the specified location on the specified element.

windowFocus() Gives focus to the currently selected window

windowMaximize() Resize currently selected window to take up the entire screen

open (url) Opens an URL in the specified browser and it accepts both relative and absolute URLs.

openWindow (url,windowID)

Opens a popup window. After opening the window, user need to activate it using the selectWindow command.

dragAndDrop (locator,movementsString)

Drags an element and then drops it based on specified distance.

dragAndDropToObject (Dragobject,dropobject)

Drags an element and drops it on another element.

Actions are commands that manipulate the state of the application.Upon execution, if an action fails the execution of the current test is stopped.

Command/Syntax Description

click (locator) Clicks on a link, button, checkbox or radio button

clickAt (locator,coordString) Clicks on an element with the help of locator and co-ordinates

close() Simulates the user clicking the "close" button in the title bar of a popup window or tab.

contextMenuAt (locator,coordString) Simulates opening the context menu of the specified element from a specified location

doubleClick (locator) Double clicks on a webelement based on the specified element.

type (locator,value) Sets the value of an input field, similar to user typing action.

typeKeys (locator,value) Simulates keystroke events on the specified element, as though you typed the value key-by-key.

echo (message) Prints the specified message on console which is used for debugging.

fireEvent (locator,eventName) Explicitly simulate an event, to trigger the corresponding "onevent" handler

focus (locator) Move the focus to the specified element

Page 19: Selenium Guide

A COMMAND TELLS SELENIUM WHAT TO DO - ACCESSORSAccessors

evaluate the state of the application and store the results in a variable which are used in assertions.

Command/Syntax Description

assertErrorOnNext (message) Pings Selenium to expect an error on the next command execution with an expected message.

storeAllButtons (variableName) Returns the IDs of all buttons on the page.

storeAllFields (variableName) Returns the IDs of all input fields on the page.

storeAllLinks (variableName) Returns the IDs of all links on the page.

storeAllWindowIds (variableName) Returns the IDs of all windows that the browser knows about in an arr

storeTitle (variableName) Gets the title of the current page.

storeValue (locator,variableName) Gets the (whitespace-trimmed) value of an input field.

storeChecked (locator, variableName) Gets whether a toggle-button (checkbox/radio) is checked.

storeElementPresent (locator, variableName) Verifies that the specified element is somewhere on the page.

storeConfirmation (variableName) Retrieves the message of a JavaScript confirmation dialog generated during the previous action.

storeElementIndex (locator, variableName) Get the relative index of an element to its parent (starting from 0).

storeSelectedValue (selectLocator,variableName) Gets value (value attribute) for selected option in the specified select element.

Page 20: Selenium Guide

A COMMAND TELLS SELENIUM WHAT TO DO - ASSERTİONSAssertions enable us to verify the state of an application

and compares against the expected.

Command/Syntax Description

waitForErrorOnNext (message) Waits for error; used with the accessor assertErrorOnNext.

verifySelected(selectLocator, optionLocator) Verifies that the selected option of a drop-down satisfies the optionSpecifier.

waitForSelected (selectLocator, optionLocator) Waits for getting the option selected; used with the accessor assertSelected.

waitForNotSelected (selectLocator, optionLocator)

Waits for not getting the option selected; used with accessor the assertSelected.

Page 21: Selenium Guide

WHAT IS DIFFERENCE BETWEEN ASSERT AND VERIFY COMMANDS?Assert: Assert command checks whether the given

condition is true or false. Let’s say we assert whether the given element is present on the web page or not. If the condition is true then the program control will execute the next test step but if the condition is false, the execution would stop and no further test would be executed.

Verify: Verify command also checks whether the given condition is true or false. Irrespective of the condition being true or false, the program execution doesn’t halts i.e. any failure during verification would not stop the execution and all the test steps would be executed.

Page 22: Selenium Guide

EXPLICIT AND IMPLICIT WAITSExplicit Waits: Defining wait for a certain condition to occur before proceeding further in code is explicit wait.

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(EnterButton));

element.click();

or

new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOf(Status));

 

Implicit Waits: An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find

an element or elements if they are not immediately available.

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Page 23: Selenium Guide

<input type="email" class="inputtext" name="email" id="email" value="“ tabindex="1">

Page 24: Selenium Guide

SELENİUM LOCATORS Method Syntax Description

By ID driver.findElement(By.id(“next”); Locates an element using the ID attribute

By name driver.findElement(By.name(<element name>))

Locates an element using the Name attribute

By class name driver.findElement(By.className(<element class>))

Locates an element using the Class attribute

By tag name driver.findElement(By.tagName(<htmltagname>))

Locates an element using the HTML tag

By link text driver.findElement(By.linkText(<linktext>))

Locates a link using link text

By partial link text driver.findElement(By.partialLinkText(<linktext>))

Locates a link using the link's partial text

By CSS driver.findElement(By.cssSelector(“.circle”))

Locates an element using the CSS selector

By XPath driver.findElement(By.xpath(“.//*[@id='canvas']”))

Locates an element using XPath query

Page 25: Selenium Guide

USING LOCATORS

Page 26: Selenium Guide

WEBELEMENT Locating elements in WebDriver can be done on the WebDriver instance itself or on a

WebElement. Each of the language bindings exposes a “Find Element” and “Find Elements” method. The former returns a WebElement object matching the query, and throws an exception if such an element cannot be found. The latter returns a list of WebElements, possibly empty if no DOM elements match the query.

@FindBy( how = How.ID, using ="startpage_status_id ") private WebElement CPUStatus; or @CacheLookup @FindBy(id = "startpage_status_id" ) private WebElement CPUStatus; @CacheLookup It means the elements of the page will be cached once searched. All

elements used in the HomePage & CPUPage class are static and are always present. So it is better to cache objects and save execution time of the test run.

Page 27: Selenium Guide

WHAT IS OBJECT REPOSITORY? HOW CAN WE CREATE OBJECT REPOSITORY IN SELENIUM?Object Repository is a term used to refer to the collection

of web elements belonging to Application Under Test (AUT) along with their locator values. Thus, whenever the element is required within the script, the locator value can be populated from the Object Repository. Object Repository is used to store locators in a centralized location instead of hard coding them within the scripts.

In Selenium, objects can be stored in an excel sheet which can be populated inside the script whenever required.

Page 28: Selenium Guide

WARNING The driver.quit() statement is required, otherwise the test continues to execute, leading to a timeout.

Page 29: Selenium Guide

TESTNG TestNG is a testing framework inspired from JUnit and

NUnit but introducing some new functionalities that make it more powerful and easier to use, such as:

• Annotations.• Run your tests in arbitrarily big thread pools with

various policies available (all methods in their own thread, one thread per test class, etc...).

• Test that your code is multithread safe.• Flexible test configuration.• Support for data-driven testing (with @DataProvider).• Support for parameters.• Supported by a variety of tools and plug-ins (Eclipse,

IDEA, Maven, etc...).• Embeds BeanShell for further flexibility.• Default JDK functions for runtime and logging (no

dependencies).• Dependent methods for application server testing.

Page 30: Selenium Guide

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

alwaysRun : For before methods (beforeSuite, beforeTest, beforeTestClass and beforeTestMethod, but not beforeGroups): If set to true, this configuration method will be run regardless of what groups it belongs to. For after methods (afterSuite, afterClass, ...): If set to true, this configuration method will be run even if one or more methods invoked previously failed or was skipped.

dependsOnGroups: The list of groups this method depends on.dependsOnMethods: The list of methods this method depends on.groups: The list of groups this class/method belongs to.inheritGroups: If true, this method will belong to groups specified in the @Test annotation at the class level.

@AfterSuite: The annotated method will be run after all tests in this suite 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. 

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

@AfterMethod: The annotated method will be run after each test method.

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

@DataProvider:Marks a method as supplying data for a test method. The annotated method must return an Object[][] where each Object[] can be assigned the parameter list of the test method. The @Test method that wants to receive data from this DataProvider needs to use a dataProvider name equals to the name of this annotation.

@Factory: Marks a method as a factory that returns objects that will be used by TestNG as Test classes. The method must return Object[].

@Listeners Defines listeners on a test class.@Parameters Describes how to pass parameters to a @Test method

@Test Marks a class or a method as part of the test.

priority : The priority for this test method. Lower priorities will be scheduled first.singleThreaded: If set to true, all the methods on this test class are guaranteed to run in the same thread, even if the tests are currently being run with parallel="methods". This attribute can only be used at the class level and it will be ignored if used at the method level. Note: this attribute used to be called sequential (now deprecated).timeOut: The maximum number of milliseconds thi test should take.expectedExceptions: The list of exceptions that a test method is expected to throw. If no exception or a different than one on this list is thrown, this test will be marked a failure.successPercentage : The percentage of success expected from this method.

TESTNG ANNOTATIONS – CONFIGURATION INFORMATION :

Page 31: Selenium Guide

MAVEN Apache Maven is a software project management and comprehension tool. Based on the concept of a project object model

(POM), Maven can manage a project's build, reporting and documentation from a central piece of information.

Create Maven Project mvn -B archetype:generate \ -DarchetypeGroupId=org.apache.maven.archetypes \ -DgroupId=com.mycompany.app \ -DartifactId=my-app

Add Selenium dependency <!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java --> <dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>2.53.1</version> </dependency>   Add TestNG Dependency <dependency>    <groupId>org.testng</groupId>    <artifactId>testng</artifactId>    <version>6.8</version>    <scope>test</scope>  </dependency>

Page 32: Selenium Guide

SETTING UP A SELENIUM-WEBDRIVER PROJECT In order to develop Selenium WebDriver scripts, the initial

configurations should be done.- Download and Install Java- Download and Configure Eclipse- Configure Selenium WebDriver

Page 33: Selenium Guide

Happy hacking, everyone! May your tests run fast and true!

Selin Gungor