The major business benefit of test automation is the increased degree of consistency and accuracy. Software development practises have undergone profound change over the years, as have methods and software.These improvements are directed at enhancing performance, efficiency and reducing turnaround times. Software testing services obviously have such an essential role to play in delivering such objectives. With the rising costs for test automation, particularly in the field of IT, and a number of automation tools available at the disposal, Selenium has stood out in this area.In this tutorial, we are going to learn about the key concepts on the selenium namely, the selenium suite, components, advantages, limitations, selenium webdriver, etc.
Selenium is a free and open source test automation tool suite that is used for automating the web applications. It promotes automation across different platforms, programming languages and browsers, etc. By taking advantage of the selenium, you can automate the test functionality and perform integration with jenkins, maven and few other continuous integration and build automation tools.
Become a master of Selenium by going through this HKR Selenium Training!
Selenium constitutes four major components, such as:
Selenium IDE is mostly renowned as a record and playback automation tool that helps in easy automation of the web applications. Moreover, it comes in the form of chrome and firefox browser extensions. Selenium IDE is based on the record and playback principle, even the users with no or little programming language can use it effectively.
Selenium Remote Control(RC) has been removed by Selenium. It was used to infuse JavaScript code into the automation browser and deemed necessary to operate automation scripts. Besides this, there were a lot of limitations like,it was indeed slow, it didn't have a headless browser like HtmlUnitDriver, and it was necessary to start the server prior to actually running the test scripts.
Selenium WebDriver is one of the most important components of the Selenium suite of tools. It comes with a gamut of advantages and supports multiple programming languages and browsers with different drivers. One Of the greatest advantage of this selenium webdriver is that it is purely based on object-oriented and provides assistance to all the major browsers such as firefox,safari, IE and chrome, etc.With the help of selenium webdriver, the scripting can be made possible in th eJava, Python and Ruby.
Now, let's go through the advantages of the selenium, they are:
Frequently asked Selenium Interview Questions and Answers !!
However,in spite of its great advantages, there are some drawbacks or limitations associated with selenium. They are:
Selenium WebDriver is the most prominent scripting tool used for automating the web applications. It does automation just by calling through a native method unlike selenium RC which performs automation by injecting the javascript in the browser. So it is much faster and greater than the selenium RC. Moreover selenium WebDriver helps in handling certain actions easily and deliberately like alerts, pop ups, jax, keyword and mouse press.
Selenium WebDriver comes with a separate driver for each and every browser it supports and calls them just through their native methods of the browsers.
In order to run the selenium test automation suite, first you need to set up the test environment. Next install java, download Eclipse and then add the selenium jar files to your eclipse project. With the help of some sample code you can test the selenium WebDriver installation.
For the step by step process of selenium Webdriver installation please go through the Selenium Webdriver Installation tutorial here.
Here, we are going to learn the selenium Webdriver commands that are used to launch different web browsers such as Safari, IE, Chrome, firefox, etc.
As you all are aware of, the Selenium WebDriver calls native methods of different browsers in order to invoke the automating scripting. So we have the different web drivers for different browsers like FirefoxDriver for Firefox browser, InternetExplorerDriver for IE, etc.
For more information regarding the code snippet to launch different browsers in selenium please go through the following link Launching Broswers Selenium.
Here we are going to learn about the need of locators and different locators used in selenium WebDriver in the process of automation.
A simple automation process in selenium can be described as follows:
The above mentioned 5 points are implemented in the below code as follows:
//Launching Firefox browser
WebDriver driver = new FirefoxDriver();
//Opening google.com
driver.get("http://www.google.com");
//Initializing webelement searchBox
WebElement searchBox = driver.findElement(By.name("q"));//Writing a text "ArtOfTesting" in the search box
searchBox.sendKeys("ArtOfTesting");
In the code, an operation is performed on the web element, we need to locate it with by.name(“q”).
There are 8 locators in selenium. They are:
WebElement element = driver.findElement(By.id("elementId"));
WebElement element = driver.findElement(By.className("objectClass"));
WebElement element = driver.findElement(By.tagName("a"));
WebElement element = driver.findElement(By.name("male"));
WebElement element = driver.findElement(By.linkText("Click Here"));
WebElement element = driver.findElement(By.partialLinkText("Click"));
7. By cssSelector – Locates the web element using css its CSS Selector patterns. In Selenium, we can use these CSS Selector rules/patterns for locating web elements and later perform different operations on them.
Syntax: WebElement element = driver.findElement(By.cssSelector("div#id"));
For example-
//Locating searchBox element using CSS Selector
WebElement searchBox = driver.findElement(By.cssSelector("div#searchBox"));
//Performing click operation on the element
searchBox.sendKeys("HKR Trainings");
WebElement element = driver.findElement(By.xpath("//div[@id='id']"));
These locators are very powerful and help in creating robust locators for complex web elements. There are some scenarios where we cannot use id attributes or locators like classNamename, in such cases,you need to take advantage of the CSS selector and XPath locators.
Related Article: Selenium vs Tosca
Here we are going to learn the basic selenium webdriver commands that helps in performing operations like opening an URL, clicking on buttons, writing in a textbox and closing the browser, etc.
Now let’s see the commands in detail:
Opening a URL:
One can open an URL by using the Get and Navigate methods.
The driver.get()method is used to navigate a webpage by using the string URL as follows:driver.get("https://hkrtrainings.com/");
The driver.navigate().to() method does the task of opening a web page like driver.get() method. driver.navigate().to("https://hkrtrainings.com/");
Click()method is used to perform the click operations on the web elements.The click() method is applied on the webElements identified, to perform the click operation.
//Clicking an element directly
driver.findElement(By.id("button1")).click();
//Or by first creating a WebElement and then applying click() operation
WebElement submitButton = driver.findElement(By.id("button2"));
submitButton.click();
The sendKeys() method can be used for writing in a textbox or any element of text input type.
//Creating a textbox webElement
WebElement element = driver.findElement(By.name("q"));
//Using sendKeys to write in the textbox
element.sendKeys("ArtOfTesting!");
The clear() method can be used to clear the text written in a textbox or any web element of text input type.
//Clearing the text written in text fields
driver.findElement(By.name("q")).clear();
In order to fetch the text written over a web element for performing some assertions or debugging. For this, we have the getText() method in selenium webDriver.
//Fetching the text written over web elements
driver.findElement(By.id("element123")).getText();
Selenium provides navigate().back() command to move backward in the browser’s history.
//Navigating backwards in browser
driver.navigate().back();
Selenium provides navigate().forward() command to move forward in a browser.
//Navigating forward in browser
driver.navigate().forward();
We can also perform a refresh of the web page in the seleniumWebdriver by using the following syntax as follows.
Here, we are going to learn about the waits in selenium and why they are used. Generally in the process of performing automation, waits are very important, because some elements get loaded while leaving some elements unloaded. In such cases elementNotFound Exception rises in order to locate the element.Thread.sleep() halts the test exception for a while and processes the next step, in automation, Thread.sleep() is not advisable. So in UI automation, waits are used to overcome such situations.
Related Article: Selenium Webdriver Commands
The implicit waits are set to the Webdriver instance that can be applied to all the web elements as whole.Here we will specify the time to throw an exception. If you are unable to locate the elements, implicit wait makes you wait till the maximum time you specified to throw an NoSuchElementException.
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
In the above code the WEbDriver waits for the maximum time specified i.e 30 seconds before through NoSuchElementException.
Explicit waits must be applied to each and every element separately.Here the conditions are stated for the WebDriver instance before locating the elements. Some conditions used in explicit waits are elementToBeClickable, presenceOfElementLocated, etc.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.presenceOfElementLocated(ElementLocator));
Here the WebDriver instance will check for the condition for the specified time period , if the condition is not met, it will throw an exception. Thus wairs play an important role in selenium WebDriver
In order to handle the drop down and multi select list using Selenium WebDriver, we need to use Select class. The Select class starts with capital S only and it is a WebDriver class that provides the implementation of the HTML SELECT TAG. It comes with Select By and Deselect By type methods that are used to select or deselect the items in the dropdown list.
The Select class is the part of the selenium package and we need to import the following library as follows.
import org.openqa.selenium.support.ui.Select;
Syntax for the Select class is as follows:
Select dropdown = new Select(
To Handle Drop Down And Multi Select List in Selenium we use the following types of Select Methods.
Related Article: Selenium WebDriver Installation
dropdown.selectByVisibleText("Database Testing");
2. selectByIndex Method:To select an option based on its index, beginning with 0.
dropdown.selectByIndex(3);
3. selectByValue Method: To select an option based on its ‘value’ attribute.
dropdown.selectByValue("Database");
In automation, right click is performed in selenium, just by performing actions like up, down or entering keys to select the desired context menu element. In order to perform the right click in selenium, we take the advantage of the Action class that is used to generate the complex gestures like right click, double click and drag and drop, etc.
Syntax to perform the right click on an element:
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.contextClick(element).perform();
Here, we are instantiating an object of Actions class. After that, we pass the WebElement to be right clicked as a parameter to the contestClick() method present in the Actions class. Then, we call the perform() method to perform the generated action.
Similar to that of performing the right click on the lament, double click is also used to perform some actions on the elements by using the actions class.
Syntax to perform the double click on the element:
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.doubleClick(element).perform();
Here, we are instantiating an object of Actions class. After that, we pass the WebElement to be double clicked as a parameter to the doubleClick() method present in the Actions class. Then, we call the perform() method to perform the generated action.
Related Article: UFT vs Selenium
In order to perform mouse hover over an element, using selenium WebDriver with java, actions class is must.
Syntax:
Actions action = new Actions(driver);
WebElement element = driver.findElement(By.id("elementId"));
action.moveToElement(element).perform();
Here, we are instantiating an object of Actions class. After that, we pass the WebElement to be mouse hovered as a parameter to the moveToElement() method present in the Actions class. Then, we will call the perform() method to perform the generated action.
In order to handle drag and drop events in the selenium WebDriver takes the advantage of the Actions class.To perform the drag and drop on an element, we need to use different methods of the Actions class namely:
The following is the code snippet for performing the drag and drop operation is stated below:
//WebElement on which drag and drop operation needs to be performed
WebElement fromWebElement = driver.findElement(By Locator of fromWebElement);
//WebElement to which the above object is dropped
WebElement toWebElement = driver.findElement(By Locator of toWebElement);
//Creating an object of Actions class to build composite actions
Actions builder = new Actions(driver);
//Building drag and drop action
Action dragAndDrop = builder.clickAndHold(fromWebElement)
.moveToElement(toWebElement)
.release(toWebElement)
.build();
//Performing the drag and drop action
dragAndDrop.perform();
Handling Alerts:
With the help of the alert class, we can handle alerts in the selenium WebDriver. Click on “Generate Alert Box” and “Generate Confirm Box” buttons to generate the alert and confirm boxes. The script below will first generate alert boxes by clicking on these buttons and use alert class methods to accept/dismiss them.
public void alertAutomation() throws InterruptedException{
//Create firefox driver's instance
WebDriver driver = new FirefoxDriver();
//Set implicit wait of 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch sampleSiteForSelenium
driver.get("https://artoftesting.com/samplesiteforselenium");
//Handling alert boxes
//Click on generate alert button
driver.findElement(By.cssSelector("div#AlertBox button")).click();
Thread.sleep(3000);
//Using Alert class to first switch to or focus to the alert box
Alert alert = driver.switchTo().alert();
//Using accept() method to accep the alert box
alert.accept();
//Handling confirm box
//Click on Generate Confirm Box
driver.findElement(By.cssSelector("div#ConfirmBox button")).click();
Thread.sleep(3000);
Alert confirmBox = driver.switchTo().alert();
//Using dismiss() command to dismiss the confirm box
//Similarly accept can be used to accept the confirm box
confirmBox.dismiss();
}
Scrolling a web page:
Scrolling an web page is needed inthe automation because the application requires scrolling up and down to show the full products list of an ecommerce store. For example, if you consider amazon ecommerce stores, if you want to look for more products, you need to scroll up or down, so that more items will be loaded on your page you are viewing.
Syntax for scrolling a web page:
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("scrollBy(0, 2500)");
There are several ways to refresh a webpage in selenium. They are :
1.Using driver.navigate() command
Syntax: driver.navigate().refresh();
2.Opening current URL using driver.getCurrentUrl() with driver.get() command
Syntax:driver.get(driver.getCurrentUrl());
3.Opening current URL using driver.getCurrentUrl() with driver.navigate() command
Syntax: driver.navigate().to(driver.getCurrentUrl());
4.Pressing F5 key on any textbox using sendKeys command
Syntax: driver.findElement(By textboxLocator).sendKeys(Keys.F5);
5.Passing ascii value of F5 key i.e. “\uE035” using sendKeys command
Syntax: driver.findElement(By textboxLocator).sendKeys("\uE035");
Selenium contains an Actions class that comes with different methods for keyboard interactions. There are 3 actions for handling the keyboard action, keyDown(),keyUP(), and sendKeys().
Related Article: What is XPath in Selenium
TestNG Basics:
What is testNG?
TestNG is a JUnit-inspired testing framework that provides a range of features such as data-driven testing, parameterization support, different utility annotations and test case aggregation that help to construct stable and efficient testing projects.
Syntax: @Test
public void sampleTest() {
//Any test logic
System.out.println("Hi! ArtOfTesting here!");
}
The different features associated with testNG are:
Next we are going to learn how to test an application using testNG. In order to perform the testing we need an automation tool, testing framework or libraries, and the programming language that supports both the tools and libraries.
For UI automation-Selenium WebDriver is perfect, testNG as the testing framework and java as the programming language.
For example if you want to automate the Google calculator feature on the chrome browser, you need to run the test on the chrome browser. For this you need to set the webdriver.chrome.driver system property and point to a chrome driver executable file-
The following is the code snippet to perform the test on the Google calculator.
public class calculatorTest {
@Test
//Tests google calculator
public void googleCalculator(){
//Creating a driver object referencing WebDriver
WebDriver driver;
//Setting the webdriver.chrome.driver property to its executable's location
System.setProperty("webdriver.chrome.driver", "/lib/chromedriver.exe");
/Instantiating driver
driver = new ChromeDriver();
//Set implicit wait of 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
//Launch google
driver.get("http://www.google.co.in");
//Write 2+2 in google textbox
WebElement googleTextBox = driver.findElement(By.id("gbqfq"));
googleTextBox.sendKeys("2+2");
//Click on searchButton
WebElement searchButton = driver.findElement(By.id("gbqfb"));
searchButton.click();
//Get result from calculator
WebElement calculatorTextBox = driver.findElement(By.id("cwos"));
String result = calculatorTextBox.getText();
//Verify that result of 2+2 is 4
Assert.assertEquals(result, "4");
}
}
An annotation is metadata that possesses information related to the class, method and interface. TestNG makes use of these annotations to provide several features that aid in the creation of a robust testing framework.
Here, we are going to learn different testNG annotations. They are:
@Test:The @Test is the most important and commonly used annotation of TestNG. It is used to mark a method as Test. So, any method over which we see @Test annotation is considered as a TestNG test.
@Test
public void sampleTest() {
//Any test logic
System.out.println("Hi! ArtOfTesting here!");
}
The annotated method will run only once before all tests in this suite have run.
The annotated method will run only once after all tests in this suite have run.
The annotated method will run only once before the first test method in the current class is invoked.
The annotated method will run only once after all the test methods in the current class have been run.
The annotated method will run before any test method belonging to the classes inside the
The annotated method will run after all the test methods belonging to the classes inside the
Using @DataProvider we can create a data driven framework in which data is passed to the associated test method and multiple iteration of the test runs for the different test data values passed from the @DataProvider method. The method annotated with @DataProvider annotation return a 2D array or object.
//Data provider returning 2D array of 3*2 matrix
@DataProvider(name = "dataProvider1")
public Object[][] dataProviderMethod1() {
return new Object[][] {{"kuldeep","rana"}, {"k1","r1"},{"k2","r2"}};
}
//This method is bound to the above data provider
//The test case will run 3 times with different set of values
@Test(dataProvider = "dataProvider1")
public void sampleTest(String str1, String str2) {
System.out.println(str1 + " " + str2);
}
The @Parameter tag is used to pass parameters to the test scripts. The value of the @Parameter tag can be passed through testng.xml file.
Sample testng.xml with parameter tag-
@Test (timeOut = 500)
Sample Test Script with @Parameter annotation-
public class TestFile {
@Test
@Parameters("sampleParamName")
public void parameterTest(String paramValue) {
System.out.println("sampleParamName = " + sampleParamName);
}
TestNG provides us different kinds of listeners using which we can perform some action in case an event has triggered. Usually, testNG listeners are used for configuring reports and logging.
@Listeners(PackageName.CustomizedListenerClassName.class)
public class TestClass {
WebDriver driver= new FirefoxDriver();@Test
public void testMethod(){
//test logic
}
}
The @Factory annotation helps in the dynamic execution of test cases. Using @Factory annotation, we can pass parameters to the whole test class at run time. The parameters passed can be used by one or more test methods of that class.
Data-driven testing can be carried out through TestNG using its @DataProvider annotation. A method with @DataProvider annotation over it returns a 2D array of the object where the rows determine the number of iterations and columns determine the number of input parameters passed to the Test method with each iteration.
This annotation takes only the name of the data provider as its parameter which is used to bind the data provider to the Test method. If no name is provided, the method name of the data provider is taken as the data provider’s name.
@DataProvider(name = "nameOfDataProvider")
public Object[][] dataProviderMethodName() {
//Data generation or fetching logic from any external source
//returning 2d array of object
return new Object[][] {{"k1","r1",1},{"k2","r2",2}};
}
After the creation of the data provider method, we can associate a Test method with a data provider using the ‘dataProvider’ attribute of @Test annotation. For successful binding of data providers with the Test method, the number and data type of parameters of the test method must match the ones returned by the data provider method.
@Test(dataProvider = "nameOfDataProvider")
public void sampleTest(String testData1, String testData2, int testData3) {
System.out.println(testData1 + " " + testData2 + " " + testData3);
}
Running tests in parallel using testNG:
We can perform the parallel processing of the tests by using the TestNG suite. In order to make the test execution of the testNG parallel, testng.xml file comes with suitetest, classes, packages with the suite being the root tag.
In order to run tests in parallel we need to add two key value pairs to the suite section as below
Multi-Browser testing:
Multi-browser testing is to support testing in multiple browsers. For this we need to use the @paramterannotation of the testNG that passes different values of the browser to test the script s from the testng.xml file.
The value of the browser parameter can then be used to instantiate the corresponding driver class of Selenium WebDriver. As the browser value is used across all the test methods so, it is better to use the browser variable in @BeforeTest method.
@Parameters("browser")
@BeforeTest
public void setBrowser(String browser)
{
if (browser.equalsIgnoreCase("Firefox")) {
driver = new FirefoxDriver();
}
else if (browser.equalsIgnoreCase("Chrome")) {
System.setProperty("webdriver.chrome.driver",
+ pathToChromeDriverBinary + "chromedriver.exe");
driver = new ChromeDriver();
}
else {
throw new IllegalArgumentException("Invalid browser value!!");
}
driver.get(URL);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
}
As discussed above the value of the browser variable will be passed to the test scripts through testng.xml file. This testng.xml file will have a parameter tag containing the browser variable and its value.
Here, we will create two tests, one each for Firefox and Chrome browser with different browser values. Refer to the below snippet of testng.xml file to understand the test parameterization concept.
Indeed, having parallel=”tests” in the Suite tag makes the two tests run in parallel.
On executing the test using testng.xml, the test will run in parallel for all the specified browsers(Firefox and Chrome in case of our example).
Assertions are used to compare the actual result with the expected ones. For example, if we had multiple assertions in our test method and wanted to execute some code after the particular assertion statement,in that scenario testNG comes with the SoftAssert class.
Syntax: SoftAssert softAssert = new SoftAssert();
If you want to limit the test execution time by specifying an upper limit of timeout exceeding which the test method is marked as a failure. TestNG provides us timeOut attributes for handling these requirements. In the @Test annotation, the timeOut attribute is specified with a particular value, if the test method exceeds that value then it shows failure by throwing the ThreadTimeoutException.
Syntax: @Test(timeOut = 1000)
Conclusion:
This tutorial will help you to a great extent even with a little or no knowledge in automation or selenium.All the concepts are explained in depth, you can gain full knowledge in performing the testing.
Batch starts on 1st Jun 2022, Weekday batch
Batch starts on 5th Jun 2022, Weekend batch
Batch starts on 9th Jun 2022, Weekday batch