Selenium

Scroll Web Page

Level4, Selenium
We can scroll the web page using JavaScript Executor in the java code. I have taken the below examples with Five different scenarios of scrolling a webpage.  Scroll Down  Scroll up  Scroll bottom of the Page  Full scroll to bottom in slow motion automatically to your Web Element 1.Scroll Down: import java.util.concurrent.TimeUnit; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; public class PageScrollDown { public static void main(String[] args) { WebDriver driver = new FirefoxDriver(); //Launching the browser application driver.get("http://www.javaseleniumworld.com/"); //Adding wait driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Maxi

Selenium Introduction

Automation, Level1, Selenium, Uncategorised
Selenium Introduction: What is Automation Testing Benefits of Automation Testing When to automate an application: Steps to follow in Automation testing: Disadvantages of Automation Testing Different Automated Web Testing Tools Selenium Introduction Selenium Pros Selenium Cons Differences between selenium and other Tools What is Automation Testing? The Process of converting Manual Test cases into Test Script by using any automation tool is known as Automation Testing. Testers write test scripts and test cases using the automation tool and then group those test cases into test suites. Benefits of Automation Testing Reliable: Tests perform precisely the same operations each time they are run, thereby eliminating human error Repeatable: You can...

Highlight Web Element in Selenium

Selenium
Why we use Highlight? Highlight plays crucial role in debugging of test script. One way to know steps being performed in browser is to highlight the web page elements. How is it possible? Core principle is to use “JavaScriptExecutor” to inject javascript into our application, which will change the CSS properties of the element at runtime and we can pinpoint (visible see) the element with changed set of properties. Scenario: Open Application: http://newtours.demoaut.com/ Highlight User Name and Password Field in Red. Java Code: import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class HighLightMe {

StaleElementReference Exception in Selenium

Selenium
StaleElementReference Exception occurs when driver is trying to perform action on the element which is no longer exists or not valid. What causes them? In short, a StaleElementException is calling a reference on an element that has been torn down.  There are many causes for them, here are some of the common ones I’ve seen. Page Refresh – I’ve seen this commonly working with tabbed pages.  Sometimes a page will look like 1 page with multiple tabs, but really are completely separate pages.  It might look like the same tab bar, but in reality you’ll have to re-find the element in order to work with it. JavaScript MVC frameworks – Many JavaScript MVC frameworks can update contents of a list or a control by rapidly tearing down and recreating the same element.  There are times an elem
CSS Selector

CSS Selector

Level3, Selenium
Locating elements by CSS Selectors There is a debate on the performance between CSS Locator and XPath locator and the debate on the performance of CSS and XPath locator is out of scope of this post. Most of the automation testers believe that using CSS selectors makes the execution of script faster compared to XPath locator. This locator is always the best way to locate elements on the page. Following are the some of the mainly used formats of CSS Selectors. Tag and ID Tag and Class Tag and Attribute Tag, Class and Attribute Sub-String Matches Starts With (^) Ends With ($) Contains (*) Child Elements Direct Child Sub-child nth child Matching By inner Text Tag and ID: Syntax: css=tag#id Open Mozilla Firefox and navigate to 
Jenkins with Selenium

Jenkins with Selenium

CICD, Level8, Popular, Selenium
Continuous Integration Continuous Integration (CI) is a development practice where developers integrate code into a shared repository frequently, preferably several times a day. Each integration can then be verified by an automated build and automated tests. While automated testing is not strictly part of CI it is typically implied. One of the key benefits of integrating regularly is that you can detect errors quickly and locate them more easily. As each change introduced is typically small, pinpointing the specific change that introduced a defect can be done quickly. In recent years CI has become a best practice for software development and is guided by a set of key principles. Among them are revision control, build automation and automated testing. “Continuous Integration doe

Data Driven Testing in TestNG

TestNG
Data Provider feature helps you to write data-driven tests, which essentially means that same test method can be run multiple times with different data-sets. It helps in providing complex parameters to the test methods as it is not possible to do this from testng.xml file. Please note that @DataProvider is the second way of passing parameters to test methods (first way we already discussed in @Parameters example). You can use it to handle a broad range of complex parameters like the following. Java objects. Objects read from a database. Data from Excel or property file etc. Facts about “@dataprovider”: This annotation has one string attribute which is its name. If you don’t specify a name, then the method’s name serves as the default name. A data provider method

Parallel Execution in TestNG

TestNG
Parallel Execution of test methods in TestNG TestNG provides multiple ways to execute tests in separate threads. In testng.xml, if we set ‘parallel‘ attribute on the tag to ‘tests‘,  testNG will run all the ‘@Test’ methods in tag in the same thread, but each tag will be in a separate thread. If we want to run methods/classes in separate threads, we need to set ‘parallel‘ attribute on the tag to ‘methods‘ / ‘classes‘ TestNG provides an ability to run test methods, test classes and tests in parallel. By using parallel execution, we can reduce the ‘execution time‘ as tests are started and executed simultaneously in different threads. **A thread is an independent path of execution within a program. Every thread in Java is created and controlled by the java.lang.Thread class.

Optional Annotation in TestNG

TestNG
Optional Annotation in TestNG As we know, we can pass parameter values to the test methods during run time from testng.xml file by specifying Parameters annotation to test method. To do this, we need to declare parameters tag in xml file using ‘name’ and ‘value’ attribute. Where the name attribute of the tag defines name of the parameter and the value attribute defines the value of the parameter. If defined parameter is not found in your testng.xml file, The test method will receive the default value which is specified inside the @Optional annotation. Syntax to define Parameter: <parameter name="param" value="Value of parameter" /> Syntax to define @Optional annotation @Parameters("browser") @Test public void method1(@Optional("Optional Value") String val

TestNG Assertions

TestNG
TestNG Assertions: While using Selenium for automated testing of web applications, we need to add validations in our tests to report them as pass or fail. And assertions can let us do that within a single line of code. Here, you’ll learn how to use TestNG assertions and know the different methods to assert conditions. Assertions give you a way, other than If-Else blocks, to test conditions. They are not only easy to use but also eliminate the chances of making any error in forming test conditions. Hence, it’s always beneficial to use them in Selenium WebDriver projects. There are two types of assertions in Selenium that we can place in our test scripts using TestNG: Hard Assertion. Soft Assertion. 1- Hard Assertion: It is the default assert mechanism built into TestNG’

TestNG Groups

TestNG
TESTNG – TEST GROUPS, META GROUP, DEFAULT GROUP   TestNG – Test Groups, Meta Group, Default Group  Grouping test methods is one of the most important features of TestNG. In TestNG users can group multiple test methods into a named group. You can also execute a particular set of test methods belonging to a group or multiple groups. This feature allows the test methods to be segregated into different sections or modules. For example, you can have a set of tests that belong to sanity test where as others may belong to regression tests. You can also segregate the tests based on the functionalities/features that the test method verifies. This helps in executing only a particular set of tests as and when required. Example: Group Test Let’s create a test class as G

CLASS LEVEL ANNOTATIONS IN TESTNG

TestNG
Class level annotations in TestNG: TestNG has the feature to define annotations on a class instead of a each test method. Let’s say there are 20 test methods, where adding @Test on a class level is simpler than adding @Test for each method. When we make class level @Test annotation, all the public methods of this class will become test methods even if they are not annotated. We can still define @Test annotation on of the method if we want to add any attributes to particular test method. Example: @Test annotation at class level: package Annotations; import org.testng.annotations.Test;@Test public class ClassLevelAnnotations { public void Register() { System.out.println("===Register TestCase Executed==="); } public void Login() { System.out.println("==

@Test Attributes

TestNG
HOW TO SKIP EXCEPTION TEST IN TESTNG Using TestNG, we have multiple ways to Skip a test based on our requirement. We can Skip complete test without executing it or we can Skip a test when a specific condition is not satisfied. Case 1: In TestNG, @Test(enabled=false) annotation is used to skip a test case if it is not ready to test. We don’t need to import any additional statements. As in JUnit, TestNG will not show you the other test method as Skipped or Ignored. It will not consider that case method at all when the annotation is mentioned as “@Test(enabled=false)”. Case 2: And We can Skip a test by using TestNG Skip Exception if we want to Skip a particular Test. Syntax: throw new SkipException(“message”); Case 3: we can also perform a CONDITIONALSkip, i.e. we can ha

Include & Exclude Tests in testng.xml

TestNG
How to Include/Exclude Selected Test Methods Using testng.xml File In this Post I will explain you, how you can include/exclude selected test methods from execution. First of all configure your Project Structure as below. Step 1: Create package = “TestNGPack1” and under this package Create classes as Program1.java and Program2.java Step 2: Create package = “TestNGPack2” and under this package Create classes as Program3.java and Program4.java Each Class containing two methods as shown in below image. Once done with above steps your Project structure will look like this.   Program1.java package TestNGPack1; import org.testng.annotations.Test; public class Program1 { //@Test annotation describes this method as a test method @Test public void TC0

testng.xml File with TestNG

TestNG
In any project, you will end up to a place where you need to execute so many test cases on a run. Running a set of test cases together is call executing a Test Suite. Those test cases can be dependent to each other or may have to be executed in a certain order. The main advantage of using TestNG framework in Selenium is its ease of running multiple tests from multiple classes using just one configuration In TestNG framework, we need to create testng.xml file to create and handle multiple test classes. Testng.xml is an XML file that describes the runtime definition of a test suite. It describes complex test definition while still remain easy to edit. Using Testng.xml file we can run test available in one or more class file and make them as a single group, hence making test more mea

TestNG Report

TestNG
TESTNG REPORTING:   A perfect test automation tool is what you need for the successful execution of the testing requirements in the Agile process. And there are multiple factors which play a critical role in the formation of a robust automation framework. One such factor is reporting which not only make you aware of the status of the success or failure but helps you in finding out the potential bugs. So, you should mindfully choose how you are going to generate reports in Selenium WebDriver project. That’s where this post would lead you to make a decision. TestNG Reporting: TestNG library brings a very convenient reporting feature. Once you execute the tests, TestNG generates a test output folder at the root of the project. It combines two kinds of reports. 1.D

TestNG With Selenium

TestNG
TestNG, as the name suggest, is the next generation test automation tool that fills the gaps in the JUnit framework. The basic idea behind the inception of these tools was to cut down the unit testing efforts during the Java development. However, these tools are now being utilized by the software testers for test-driven development. Since TestNG is the new entrant, it brings a list of cool features like TestNG annotations, parallel execution, test case management, effective reporting and much more. Interestingly, there is a TestNG plugin that we can integrate with the Eclipse IDE and instantly start creating TestNG projects in Eclipse.   How to Install TestNG in Eclipse IDE Just to talk a little about the TestNG features such as annotations, they are like the small hooks ye
Excel Sheet in Selenium

Excel Sheet in Selenium

Level6, Selenium
HOW TO READ DATA FROM EXCEL FILE USING APACHE POI How to Read Data from Excel File Using Apache POI Java provides us different classes for File Manipulation with Selenium. In this tutorial, we are going to learn how can we read and write on Excel file with the help of Java IO package and Apache POI library. To read or write an Excel,Apache provides a very famous library POI. This library is capable enough to read and write both XLS and XLSX file format of Excel. To read XLS files, an HSSF implementation is provided by POI library. To read XLSX, XSSF implementation of POI library will be the choice. Before writing program you need to download the POI Jar files and import into your Project. You can simply download the latest version POI jars from http://poi.apache.
Cookies in selenium

Cookies in selenium

Level5, Selenium
Cookies: Cookie is a piece  of information from website and saved by your web browser Cookies are a way of remembering users and their interaction with the site by storing information in the cookie file as key value pairs. It stores the login information like user name / email and password HTTP cookie is also known as a web cookie, a browser cookie or Internet cookie. One website cannot access the cookies set by other websites   Handling Cookie in Selenium : Each cookie is associated with a name, value, domain, path, termination, and status of whether it is safe or not. We validate the cookie using selenium,  selenium can parse all the cookies When testing a web application using the Selenium, you may need to create, update or delete a cookie to check the
Dropdowns in Selenium

Dropdowns in Selenium

Level4, Selenium
1.Select Class in Selenium WebDriver. 2.Different Select Methods       i.selectByVisibleText Methods.       ii.selectByIndex Method.       iii.selectByValue Method. 3.Different DeSelect Methods.       i.deselectByIndex Method.       ii.deselectByValue Method.       iii.deselectByVisibleText Method.       iv.deselectAll Method. The most basic approach for handling these elements is first to locate their element <group>. We’ve labeled it as a <group> because none of the Dropdown and Multiple Select is a singular entity. They do have the same identity which serves to hold more than one element. You can simply think both of them as containers for holding multiple options. The only difference between the Dropdown and Multiple Select fields is the deselecting state
iFrames in Selenium

iFrames in Selenium

Level5, Selenium
How To Handle Frames In Selenium Webdriver How To Handle Frames In Selenium Webdriver: Occasionally you will encounter the below error when trying to locate an element. One of the reason might be that the element is present within a frame. And when writing a test against them, you can easily get tripped if you’re not paying attention. You cannot directly identify an element present in an iFrame. First we have to switch to the frame and then we can identify the elements present using normal Selenium locators. In this article let’s see how to handle frames in Selenium Webdriver. Error: Exception in thread “main” org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {“method”:”id”,”selector”:”tinymce”} What is iFrame? A web page which i
Webdriver Listeners in Selenium | WebDriverEventListener

Webdriver Listeners in Selenium | WebDriverEventListener

Level7, Selenium
Webdriver Listeners in Selenium : Event listener in WebDriver helps to tack event those we trigger and by using these we could get a better idea of sequential order of actions . Listeners are  helpful for logging and exception section. Suppose you are trying to track exception and the same time wants to take screenshot. Instead of hard-coding logging requests all over the place, we can leverage an event listener to give us the information we want If you think, Listeners are only useful in logging then you are wrong, it more helpful on pre and post steps of a action in selenium webdriver. Selenium provide WebDriverEventListener interface for listening event in selenium, WebDriverEventListener Interface provide methods, which covers most of the actions (not all) in selenium we
Navigation Commands in Selenium | To() | back() | forward() | refresh()

Navigation Commands in Selenium | To() | back() | forward() | refresh()

Level1, Selenium
Navigation Commands : Navigation commands are used to navigate from one web page to another web page, Navigation commands also helps to navigate through browser history like back forth or to refresh the current page.   To() : If you wants to navigate on specific web application page or URL in between your software test then you can use driver.navigate().to('url") command . driver.navigate().to("http://google.com/"); Back(): We can go back to previous page with driver.navigate().back() command. driver.navigate().back(); Forward(): We can go forward from current page to last opened page with driver.navigate().next() command, but for using forward() method, you must have navigated back first. driver.navigate().forward(); Refresh(): We can refresh
Open Browser in Selenium

Open Browser in Selenium

Automation, Level1, Selenium
Opening a browser with binary File: There will be situations, where you have to test your web application against two different versions of the  browser. For example consider FireFox, By default, when you create object to FirefoxDriver, the Firefox version that is available on the PATH variable is launched. But if you want to launch a different version of Firefox, we need to use Firefox Binary, or if the browser is not in the standard PATH then you should specify the browser binary file location to open the browser. public static void main(String[] args) { File pathToBinary = new File("C:\\PATH\\App\\Firefox\\firefox.exe"); FirefoxBinary firefoxBinary = new FirefoxBinary(pathToBinary); FirefoxProfile firefoxProfile = new FirefoxProfile(); WebDriver driver = new Firefo
Pop Ups in Selenium

Pop Ups in Selenium

Level4, Selenium
How To Handle Javascript Alerts/PopUps In Selenium WebDriver: In this post, we see how to handle javascript alerts/popus. Alerts are basically popup boxes that take your focus away from the current browser and forces you to read the alert message. You need to do some action such as accept or dismiss the alert box to resume your task on the browser. To handle alerts popupswe need to do switch to the alert window and call Selenium WebDriver Alert API methods. There are two types of alerts. Windows Based Web Based/Browser Based Here in this post, I confine to Java Script Alerts (A.K.A. Browser/Web Based Alerts). To handle Browser based Alerts (Web based alert popups), we use Alert Interface. The Alert Interface provides some methods to handle the popups. While runnin
Robot Class in Selenium

Robot Class in Selenium

Level7, Selenium
Robot Class in Selenium : Robot Class is available under java.awt.package, Robot class is a Java class which helps the Java developer to emulate the Mouse and Keyboard like actual user, also robot class helps to take screenshot of the desktop Some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. So, we need to use either AutoIT or Robot class in Selenium Webdriver to interact the Windows Dialog boxes like upload and download.   Use of Robot Class in Selenium: Robot class emulates real user in front of the computer Using Robot Class we can handle keyboard and mouse events in Selenium. Robot ...

Screenshots in Selenium

Level5, Selenium
Most of the time we think to Capture Screenshot in WebDriver when some kind of error or exception surfaces while practicing testing, to resolve the same WebDriver has provided us one interface TakesScreenshot for capturing the screenshot of web application and This interface provides one method names as getScreenshotAs() to capture screenshot in instance of driver. This getScreenshotAs() method takes argument of type OutputType.File  or  OutputType.BASE64  or  Output.BYTES. We have taken the screenshot with the help of getScreenshotsAs() method and  and now it’s time to copy this file somewhere in our file system or in our desktop. So for this purpose we further use copyFile() method of the FileUtils class. Let’s create a program that will take a screenshot of the page in PNG form
TestNG in Selenium

TestNG in Selenium

Level3, Popular, Selenium
TestNG Annotations : Annotations are nothing but a piece of instruction for the compiler that you apply to classes, methods or variables in your Java code. It is a powerful feature and an integral part of the TestNG framework.  The TestNG annotations extend the same concept and control the execution sequence of the test code and test methods   List of Annotations in TestNG: TestNG Annotations Description @Test Attaches a class or a method to become the part of the test. @BeforeTest Instructs the method to run before any test method related to the classes which are inside the <test> tag as per the testng.xml file @AfterTest Halts a method from execution till all the test methods finish their execution. These methods belong to the classes defined
Xpath in Selenium

Xpath in Selenium

Level2, Selenium
What is XPath : XPath (XML path) is the language for nodes in an XML document. Since many browsers support XHTML, we can use XPath to find items on web pages. XPath helps in finding direction of element through nodes and its attributes. in HTML pages.   Syntax of XPath:   Using tag and attributes It is possible to locate a specific web element with its HTML tag, its attributes such as Id, name, class, title, value, href, src etc., and their corresponding values. Syntax: "//tagName[@attribute='value']"; Identifies the element pointed by the XPath. ‘//’ identifies the specified node and ‘@’ symbol is used to select the specified attribute which matches the given value. //input[@name='FirstName'] //input[@id='abc']   Xpath with Index: By providing

ElementNotVisible Exception

Selenium
Selenium ElementNotVisibleException is also one of the frequent exceptions which we will face in selenium webdriver while automating any kind of application. This exception tells you that the WebElement that you are trying to interact with is not visible to the user. If the element is not visible to the user then they are not going to able to interact with it   Below are the causes to face this exception: Thrown to indicate that although an element is present on the DOM, it is not visible, and so is not able to be interacted with. To overcome this kind of situation we need to use synchronization concept in selenium. So, add an explicit wait to wait for the correct conditions to be met before trying to interact with the element. We have an option to use wait in so many ways ...

NoSuchWindow Exception

Selenium
Selenium NoSuchWindowException is similar to NoSuchFrameException, this is also one of the frequent exceptions which we will face in selenium webdriver.   Sometimes applications will have child windows(i.e. Separate windows) which will open when you click on any link or button.   Normally if you want to automate the child windows then you need to switch to that window then only you can interact with the elements which are there on that window.   To overcome this, we need to handle the opened windows using one of the webdriver methods called “driver.getWindowHandles()”.   Once  you have this information then you can switch to the corresponding window to automate or interact with the window.     Below are the causes to face this ex

NoSuchFrameException

Selenium
Selenium NoSuchFrameException will discuss about one of the frequent exceptions which we will face in selenium webdriver. You might face this kind of exception while automating the application if you have iFrames in your application.   In modern applications people are using iFrames very frequently as if you want to show the information from other sources then will use the frames in the application.   We will face this kind of exception in different kind of scenarios. Will discuss the reasons for this issue and we will know we can overcome this issue.     Below are the causes to face this exception: Let’s assume in your application if you have a frame and it contains some elements (for example we will take a textbox in this scenarios) and you wan

NoSuchElementException in Webdriver

Selenium
Selenium NoSuchElementException is the most and frequent facing exception. You will definitely find this kind of exception while automating the application. In this blog we will see what are the reasons to face this exception and how we can overcome this exception in detail.   Below are the reasons to get this exception: The locator which you are using to locate the element is incorrect/changed. The element which you are looking is not rendered. Trying to find the element before it was rendered.   Locator is Incorrect/changed: Here we have two possibilities that the locator which you have written to identify an element may be incorrect or sometimes after writing/capturing the code, if there are any changes in the application then the locator may change. ...
Exceptions in Webdriver

Exceptions in Webdriver

Level7, Selenium
In this tutorial, we  will discuss about what kind of exception we will get in selenium webdriver while executing the automation scripts. An exception is an infallible statement; it will always tell you why something has gone wrong in the code.   It may not always be easy to understand the exception, but it does always tell the information about the what is wrong in the code.   One of the good things in selenium is while looking into the exception we will come to know what went wrong as the exception names will give some what clear picture for the error which we will face.   Below are some of the Exceptions which we will see while automating the applications: NoSuchElementException NoSuchFrameException NoSuchWindowException ElementNotVisibleEx
JavaScript Executor in Selenium

JavaScript Executor in Selenium

Level7, Selenium
As JavaScript Executor is an interface so we cannot create an object to this, for this we will type caste to driver object using below syntax:   JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript(javaScript, arguments); Now we will see some of the examples below that how we can use JavaScriptExecutor to execute the JavaScript to interact with the web elements.   1. How to enter value into textbox: JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.getElementById('email').value='[email protected]'");   2. How to click a button: JavascriptExecutor js = (JavascriptExecutor)driver; js.executeScript("document.querySelector('#enterimg').click()");   3. How to refresh a window: JavascriptExecutor js = (Javascri...
WebElement Actions

WebElement Actions

Automation, Level1, Selenium
In this selenium tutorial , we will learn all the different user actions that can be performed on an WebElement. Different WebElements will have different actions that can be taken on them. For example, in a textbar element, we can type in some text or clear the text that is already typed in it. Similarly for a button, we can click on it, get the dimensions of it, and position of it on the webpage, but we cannot type into a button, and for a link, we cannot type into it. All the actions are present as method in WebElement interface in selenium webdriver. In case we try to execute a wrong action on a WebElement, we don’t see any exception or error thrown and also we don’t see any action that really gets executed; WebDriver ignores such actions. The getAttribute() method The ge