TestNG Programming Question
Questions:
Q1: Action Class
Q2: Handle Select / multi Select from dropdown/ select all checkboxes/ deselect checkbox.
Q3: Alert Handle / Handle PopUps / upload - downloads file from Windows
Q4: Desire Capability
Q5: Screenshot on Failed
Q6: Internet Explorer/ chrome/ firefox Capabilities
Q7: How can use different browser
Q8: Read excel file using jxl / poi (read Last row | login with excel)
Q9: Locators in selenium
Q10: Java / JavaScript Executer command
Q11: Extent Reports
Q12: Boundry value analysis
Q13: TestNG Anotations
Q14: TestNG Parameter
Q15: Execute Selenium grid/hub/client command line
Q16: Read Excel
Q17: Parameterization in TestNG
Q18: Read & Display Dynamic WebTable Data
Read & Display Dynamic WebTable given column Data
Q19: Selenium Grid Example
Q20: Selenium Cookies Actions
Q21:
Q22:
Q23:
Q24:
Q25:
Q1) Selenium Actions Class:
Class Actions:
java.lang.Object
org.openqa.selenium.interactions.Actions
Method Summary:
- build()
Generates a composite action containing all actions so far, ready to be performed (and resets the internal builder state, so subsequent calls to build() will contain fresh sequences).
- click()
Clicks at the current mouse location.
- click(WebElement onElement)
Clicks in the middle of the given element.
- clickAndHold()
Clicks (without releasing) at the current mouse location.
- clickAndHold(WebElement onElement)
Clicks (without releasing) in the middle of the given element.
- contextClick()
Performs a context-click at the current mouse location.
- contextClick(WebElement onElement)
Performs a context-click at middle of the given element.
- doubleClick()
Performs a double-click at the current mouse location.
- doubleClick(WebElement onElement)
Performs a double-click at middle of the given element.
- dragAndDrop(WebElement source, WebElement target)
A convenience method that performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
- dragAndDropBy(WebElement source, int xOffset, int yOffset)
A convenience method that performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.
- keyDown(Keys theKey)
Performs a modifier key press.
- keyDown(WebElement element, Keys theKey)
Performs a modifier key press after focusing on an element.
- keyUp(Keys theKey)
Performs a modifier key release.
- keyUp(WebElement element, Keys theKey)
Performs a modifier key release after focusing on an element.
- moveByOffset(int xOffset, int yOffset)
Moves the mouse from its current position (or 0,0) by the given offset.
- moveToElement(WebElement toElement)
Moves the mouse to the middle of the element.
- moveToElement(WebElement toElement, int xOffset, int yOffset)
Moves the mouse to an offset from the top-left corner of the element.
- pause(long pause)
Deprecated.
'Pause' is considered to be a bad design practice.
void perform()
A convenience method for performing the actions without calling build() first.
- release()
Releases the depressed left mouse button at the current mouse location.
- release(WebElement onElement)
Releases the depressed left mouse button, in the middle of the given element.
- sendKeys(java.lang.CharSequence... keysToSend)
Sends keys to the active element.
- sendKeys(WebElement element, java.lang.CharSequence... keysToSend)
package mypackage;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class myclass {
public static void main(String[] args) {
String baseUrl = "http://newtours.demoaut.com/";
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement link_Home = driver.findElement(By.linkText("Home"));
WebElement td_Home = driver
.findElement(By
.xpath("//html/body/div"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr/td"
+ "/table/tbody/tr"));
Actions builder = new Actions(driver);
Action mouseOverHome = builder
.moveToElement(link_Home)
.build();
String bgColor = td_Home.getCssValue("background-color");
System.out.println("Before hover: " + bgColor);
mouseOverHome.perform();
bgColor = td_Home.getCssValue("background-color");
System.out.println("After hover: " + bgColor);
driver.quit();
}
}
Q2:- DropDown & Multiple Select Operations:
- import org.openqa.selenium.support.ui.Select' package and to use it we need to create a new Select Object of class Select.
- Select oSelect = new Select();
- Select Commands:-
- oSelect.selectAll();
- oSelect.selectByIndex(int index);
- oSelect.selectByValue(string value);
- oSelect.selectByVisibleText(String text);
- oSelect.getAllSelected();
- oSelect.getFirstSelectedOption();
- oSelect.getOptions();
- oSelect.isMultiple();
- oSelect.deselectByIndex(int index);
- oSelect.deselectByValue(string value);
- oSelect.deselectByVisibleText(String text);
- oSelect.deselectAll();
- MultiSelect With array Values
@Test
public void selectDDLByArrayValue(){
Commands.sleep("5000");
WebElement budget = driver.findElement(By.id("budget"));
WebDriverWait wait= new WebDriverWait(driver,50);
wait.until(ExpectedConditions.elementToBeClickable(budget));
String multiValue[]= {"Below ₹ 4000","₹ 20001 - ₹ 30000","Above ₹ 50000"};
System.out.println("--------- Budget DDL Found ----------");
Commands.sleep("1000");
Select oSelect =new Select(budget);
System.out.println("Is DDL is MultiSelected:- "+oSelect.isMultiple());
Actions builder = new Actions(driver);
Commands.sleep("5000");
System.out.println(" Wait 4 First element... ");
List options = oSelect.getOptions();
// 1st Method Using size in loop
int size= options.size();
System.out.println("Total Element in DDL: "+size);
for(int i=0; i<size; i++){
String sValue =oSelect.getOptions().get(i).getText();
for(String valueToBeSelect: multiValue){
if(sValue.equalsIgnoreCase(valueToBeSelect)){
System.out.println(valueToBeSelect+ " to be Selected ---");
builder.keyDown(Keys.CONTROL);
oSelect.selectByVisibleText(valueToBeSelect);
System.out.println(valueToBeSelect+ " Selected ---");
Commands.sleep("2000");
}
}
}
// 1st Method End Using size in loop
// 2nd option
for (String valueToBeSelect: multiValue) {
for (WebElement option : options) {
final String optionText = option.getText().trim();
if (valueToBeSelect.equalsIgnoreCase(optionText)) {
if (isMultiple) {
if (!option.isSelected()) {
builder.click(option);
}
} else {
option.click();
}
break;
}
}
}
// 2nd option end
builder.keyUp(Keys.CONTROL).build().perform();
Commands.sleep("20000");
}
- MultiSelect Without array Values
@Test
public void selectDDL(){
Commands.sleep("5000");
WebElement budget = driver.findElement(By.id("budget"));
//List budgets = driver.findElements(By.id("budget"));
WebDriverWait wait= new WebDriverWait(driver,50);
wait.until(ExpectedConditions.elementToBeClickable(budget));
System.out.println("--------- Budget DDL selected ----------");
Commands.sleep("1000");
Select oSelect =new Select(budget);
// oSelect.selectByValue("4001-10000");
// oSelect.selectByIndex(3);
// Commands.sleep("2000");
// oSelect.selectByVisibleText("₹ 30001 - ₹ 50000");
// Commands.sleep("2000");
// oSelect.getOptions();
System.out.println("Is DDL is MultiSelected:- "+oSelect.isMultiple());
Commands.sleep("5000");
System.out.println(" Wait 4 First element... ");
List options = oSelect.getOptions();
int size= options.size();
System.out.println(size);
for(int i=0; i<=size; i++){
String sValue =oSelect.getOptions().get(i).getText();
System.out.println(sValue+ " Selected ---");
oSelect.selectByVisibleText(sValue);
Commands.sleep("2000");
}
Commands.sleep("8000");
oSelect.deselectAll();
Commands.sleep("20000");
}
Q2: MultiSelect CheckBox Selection
- List oCheckBox = driver.findElements(By.name("tool"));
int iSize = oCheckBox.size();
for(int i=0; i < iSize ; i++ ){
// Store the checkbox name to the string variable, using 'Value' attribute
String sValue = oCheckBox.get(i).getAttribute("value");
// Select the checkbox it the value of the checkbox is same what you are looking for
if (sValue.equalsIgnoreCase("toolsqa")){
oCheckBox.get(i).click();
// This will take the execution out of for loop
break;
}
Q3) Handle Alert:
Q3 ii) Handle Multi PopUp Windows:
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WindowHandle_Demo {
public static void main(String[] args) throws InterruptedException {
WebDriver driver=new FirefoxDriver();
//Launching the site.
driver.get("http://demo.guru99.com/popup.php");
driver.manage().window().maximize();
driver.findElement(By.xpath("//*[contains(@href,'popup.php')]")).click();
String MainWindow=driver.getWindowHandle();
// To handle all new opened window.
Set s1=driver.getWindowHandles();
Iterator i1=s1.iterator();
while(i1.hasNext()) {
String ChildWindow=i1.next();
if(!MainWindow.equalsIgnoreCase(ChildWindow)){
// Switching to Child window
driver.switchTo().window(ChildWindow);
driver.findElement(By.name("emailid")).sendKeys("gaurav.3n@gmail.com");
driver.findElement(By.name("btnLogin")).click();
// Closing the Child Window.
driver.close();
}
}
// Switching to Parent window i.e Main Window.
driver.switchTo().window(MainWindow);
}
}
Q4: DesiredCapability Example:
- http://testingpool.com/desiredcapabilities-in-selenium-with-example/
- DesiredCapabilities help to set the properties for WebDriver.
- A typical example can be to set the path of FirefoxDriver if local installation doesn’t point to the default settings.
- Capabilities are nothing but a series of key/value pairs that express the essential features of a browser.
- 1. Using the preferred browser: The usual way to start a FirefoxDriver is as given below.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
WebDriver driver = new FirefoxDriver();
Now, let’s see how use desiredcapabilities to set the browser preferences. Use the below code for setting browser preference.
DesiredCapability setting browserJava
import org.openqa.selenium.remote.DesiredCapabilities;
DesiredCapabilities dc=DesiredCapabilities.firefox();
Webdriver driver = new FirefoxDriver(dc);
- 2. Changing the Proxy of the system: The preferred way to set the proxy manually at the system. But because of some reason , if you are not able to do so. Then you can use desiredcapabilities to set the proxy at your system to run the tests. But remember , this proxy changes in only for run time. Once the execution is over ,System will come to its original state.
Use the below code for setting proxy.
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class ChangeProxyExample {
public static void main(String[] args) {
String PROXY = "localhost:8080";
Proxy proxy = new Proxy();
proxy.setHttpProxy(PROXY)
.setFtpProxy(PROXY)
.setSslProxy(PROXY);
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(CapabilityType.PROXY, proxy);
WebDriver driver = new FirefoxDriver(cap);
//can set for other browser like internet explorer
//WebDriver driver = new InternetExplorerDriver(cap);
}
}
- 3. FirefoxProfile at run time with desired capabilities: In the previous post, we have seen how to use custom Firfox profile created by Firefox Profile Manager. We can also create desired firefox profile at run time and set the preferences.
We can create this Firefox profile for activities like to ignore untrusted certificates errors, downloading file without popping up the download box( We will learn in details about file downloading in coming posts) etc.
Create Firefox Profile:
FirefoxProfile profile = new FirefoxProfile();
profile.setAcceptUntrustedCertificates(false);
profile.setAssumeUntrustedCertificateIssuer(true);
profile.setPreference("browser.download.folderList", 2);
profile.setPreference("browser.helperApps.alwaysAsk.force", false);
Example to use Firefox profile with desired capabilities:
DesiredCapabilities caps=DesiredCapabilities.firefox();
FirefoxProfile profile = new FirefoxProfile();
caps.setCapability(FirefoxDriver.PROFILE, profile);
Webdriver driver = new FirefoxDriver(caps);
- 4. Can be helpful in selenium Grid: Selenium Grid is helpful to provide parallel testing of the test cases. It can have multiple browser instances , different browser types and platforms. (You can learn about selenium Grid in next upcoming posts.)
DesiredCapability can help to select the browser and platform preferences as given below in the table.
Key Type Description
browserName string We can set the preferred browser name like (android|chrome|firefox|htmlunit|internet explorer|iPhone|iPad|opera|safari).
version string The browser version, or the empty string if unknown.
platform string It is used to specify the particular operating system or platform where test cases will be executing.Its values could be (WINDOWS|XP|VISTA|MAC|LINUX|UNIX|ANDROID). If platform is unknown , keyword ANY could be specified.
Example of using DesiredCapabilities in selenium Grid:
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class DesiredCapabilityExample {
public static void main(String[] args) throws MalformedURLException {
DesiredCapabilities caps = new DesiredCapabilities().firefox();
caps.setVersion("30");
caps.setPlatform(Platform.WIN8);
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), caps);
}
}
capability.setPlatform(Platform.MAC); //Set platform to OSX
capability.setPlatform(Platform.LINUX); // Set platform to Linux based systems
capability.setPlatform(Platform.WINDOWS); //Set platform to Windows
capability.setPlatform(Platform.VISTA); //Set platform to VISTA
capability.setPlatform(Platform.WIN8); //Set platform to Windows
Java
capability.setPlatform(Platform.WIN8_1); //Set platform to Windows 8.1
- Code to define Desired Capabilities with multibrowser:
URL hubUrl = new URL(prop.hubURL);
DesiredCapabilities capabilities = null;
if(browser.equalsIgnoreCase("firefox")){
System.out.println("Started Firefox");
capabilities= DesiredCapabilities.firefox();
capabilities.setBrowserName("firefox");
capabilities.setPlatform(Platform.WINDOWS);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("iexplore")){
System.out.println("Started IExplore");
//File file = new File("C:\\CSSframework\\framework\\lib\\IEDriverServer_32.exe");
System.setProperty("webdriver.ie.driver","C:\\CSSframework\\framework\\lib\\IEDriverServer.exe");
capabilities= DesiredCapabilities.internetExplorer();
capabilities.setCapability( InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
capabilities.setBrowserName("iexplore");
capabilities.setPlatform(Platform.WINDOWS);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("chrome")){
System.out.println("Started Chrome");
System.setProperty("webdriver.chrome.driver","C:\\CSSframework\\framework\\lib\\chromedriver.exe");
capabilities= DesiredCapabilities.chrome();
capabilities.setBrowserName("chrome");
capabilities.setPlatform(Platform.WINDOWS);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("safari")){
System.out.println("Started Safari");
capabilities= DesiredCapabilities.safari();
capabilities.setBrowserName("safari");
capabilities.setPlatform(Platform.MAC);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("opera")){
System.out.println("Started Opera");
capabilities= DesiredCapabilities.opera();
capabilities.setBrowserName("opera");
capabilities.setPlatform(Platform.WINDOWS);
//capability.setVersion("");
}
if(browser.equalsIgnoreCase("android")){
System.out.println("Android");
//System.setProperty("webdriver.android.driver","android-server-2.32.0.apk");
capabilities= DesiredCapabilities.android();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);
capabilities.setBrowserName("android");
capabilities.setPlatform(Platform.ANDROID);
//capabilities.setVersion("4.4");
}
//AndroidDriver driver=new AndroidDriver(hubUrl, capabilities);
WebDriver driver = new RemoteWebDriver(hubUrl, capabilities);
Capabilities caps = ((RemoteWebDriver) driver).getCapabilities();
Q) DesiredCapabilities:
- The desired capability is a series of key/value pairs that stores the browser properties like browsername, browser version, the path of the browser
driver in the system, etc. to determine the behaviour of the browser at run time.
- It is a class in org.openqa.selenium.remote.DesiredCapabilities package.
- It gives facility to set the properties of browser. Such as to set BrowserName, Platform, Version of Browser.
- Desired capability can also be used to configure the driver instance of Selenium WebDriver.
- Mostly DesiredCapabilities class used when do we used Selenium Grid.
- We have to execute mutiple TestCases on multiple Systems with different browser with Different version and Different Operating System.
- Different types of Desired Capabilities Methods:
-
WebDriver driver;
String baseUrl , nodeUrl;
baseUrl = "https://www.facebook.com";
nodeUrl = "http://192.168.10.21:5568/wd/hub";
DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WIN8_1);
driver = new RemoteWebDriver(new URL(nodeUrl),capability);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);
Q8: Read Excel File from java/ selenium
Read excel file
package ExcelRead;
import java.io.File;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import org.testng.annotations.Test;
public class TestReadExcel {
@Test
public void readExcelFile() throws IOException, InterruptedException, BiffException {
System.out.println("\nExcel File Read function executing ..\n");
Thread.sleep(5000);
File file= new File("/home/adhran/workspace/WebDriverTest/files/AdminCredentials.xls");
String filePath ="/home/adhran/workspace/WebDriverTest/files/AdminCredentials.xls";
try{
FileInputStream ifile= new FileInputStream(filePath);
Workbook wb = Workbook.getWorkbook(ifile);
Sheet st= wb.getSheet(0);
int noOfRows= st.getRows();
int noOfColumns= st.getColumns();
System.out.println("No of Rows and columns in file: "+ noOfRows +" , "+ noOfColumns);
System.out.println("All Data in sheet : ");
// to get all column value from excel file
for(int i =0; i< noOfRows; i++){
for(int j=0; j< noOfColumns ; j++){
System.out.println( st.getCell(j,i).getContents());
}
}
// to get single column value from excel file
Cell cl = st.getCell(0,0);
String data1= cl.getContents();
System.out.println("Sheet Data is : " + data1);
} catch(Exception e){
System.out.println(e + " :- Error Found!");
}
Thread.sleep(5000);
}
}
Q: We will use Firefox browser in our demos. The same methods will work for all other browsers.
There are 2 ways, you can open the application in the browser.
1- get() method
2- navigate() method
1. get() method:
After opening the browser, we need to use the below method to open any particular application. This methods requires the URL of the application.
driver.get(“URL of the application”);
Don't Forget Note Means Important Remember Forgetting
URL should start with Http: instead of WWW. If URL starts with ‘WWW’, then selenium does not open it.
e.g. Valid is http://www.gmail.com
Invalid is www.gmail.com
Code for using get method to open Gmail application:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenBrowsers {
private static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.get("http://www.gmail.com");
}
}
2. navigate() method:
This is another method which can be used to open the application.
driver.navigate().to(“URL of application”);
Code for using navigate function to open application:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class OpenBrowsers {
private static WebDriver driver;
public static void main(String[] args) {
driver = new FirefoxDriver();
driver.navigate().to("http://www.gmail.com");
}
}
What is the difference between get() method and navigate() method?
The difference is that if you use navigate, it allows you to go forth and back into history of the browser,refresh the browser etc. It is not possible if using get() method.
driver.navigate().back(); // Perform backward function of browser
driver.navigate().forward(); // Perform forward function of browser
driver.navigate().refresh(); //refresh the browser
Q: Count total links on the page.
public class ExampleFindElements {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://google.com");
List totalLinks = driver.findElements(By.tagName("a"));
System.out.println("Total links : "+totalLinks.size()); // total links
}
}
Q: Xpath functions:
function name list:
1- count()
2- contains()
3- start-with()
4- ends-with()
5- substring()
6- last()
7- position()
8-
http://testingpool.com/object-identification-using-xpath-in-selenium
-> How to write if we have multiple properties?
- //input[@name=’lastname’ and @placeholder=’Last Name’]
Develop XPATH using last(): This is used to select last node of any specific type in the document or under its parent node.Let’s see how to use it.
html/body/input[last()] -- It will select the last input tag which is a submit button in our application.
//input[last()] -- This will select the last input tag in each of the parent node.
//input[last()-1] -- If we subtract 1 from last(), it will select previous one from the last input tag in each parent node. Which is last name in out case.
- Usage of count function: By using count function, you can count the total no. of specific tag in the HTML document. As we have total 5 input tags, it shows the count as 5.
count(//input)
-Usage of position Function: Select the node on the basis of the position or index relative to all nodes. Look at the below example for understanding.
//span/input[position()=1]
- Develop XPATH using contains keyword: The contains keyword finds the specified value in the whole property value. If it finds, it will return the matching node otherwise says no match found.
//input[contains(@name,’first’)]
It might be useful if we have any property value which is dynamically changing. Take an example of First name edit box, suppose its name property value having some numeric value added in the end which can be changed in next execution (Refer the fig 1.5). In that case, we can use contains.
-Develop XPATH using starts-with Keyword:
We can take the above example again , where we can verify if name property start with the value “first” or not. If true, returns matching node else match not found.
Syntax:
//input[starts-with(@name,’first’)]
Develop XPATH using ends-with keyword: The keyword ends-with does not support Xpath 1.0, rather it has been included from Xpath 2.0. If your browser does not support Xpath 2.0, below expression will not work.
//input[ends-with(@name,’1234′)]
But we have its alternative as given next using substring function.
Develop xpath using substring function: We can use the substring function in the way, the ends-with would have worked. Look at the below syntax for understanding where it is verifying if last 4 characters in the string ends with ‘1234’.
We have also used string-length function to calculate the length of the string (“firstname1234).
//input[substring(@name, string-length(@name) -3) = “1234”]
Q: Difference between WebDriver and Selenium RC:
Selenium WebDriver:
Selenium WebDriver do not need Selenium server to execute tests.
Selenium WebDriver is simpler and having more concise programming interface.
WebDriver directly interacts with the Browser itself.
It supports almost all the latest version of different browsers.
WebDriver supports Web Applications as well as mobile applications.
WebDriver provides a better support to execute Ajax applications (In ajax, element of the webpage will be loaded without browser loading or refresh).
Selenium WebDriver
Interaction between WebDriver and browser
Selenium RC:
Selenium RC required Selenium server to executes the tests.
Selenium Server used to serve as a middle man between browser and client libraries.
There were some limitation when needed to work with dialog,pop-ups etc.
Selenium supports only web Applications.
Supported all browsers but not the latest versions.
It used to inject selenium core into browser to pass the java script commands to the browser.
It is not being used now as WebDriver has come. But still some maintenance projects are supported by this.
Selenium RC
Selenium server sets communication between browser and client lib
More details about selenium WebDriver:
Selenium WebDriver can be implemented by many classes which simplifies the code to write for automation. Selenium jars files can be configured with any desired IDE like IntelliJ IDEA or Eclipse.If a person knows core java , he/she should be able to start writing code using Selenium WebDriver.
It provides synchronization during script, handle native event on browsers. This is the main interface used for testing, having following implementing classes.
ChromeDriver
EventFiringWebDriver
AndroidDriver
AndroidWebDriver
FirefoxDriver
HtmlUnitDriver
InternetExplorerDriver
IPhoneDriver
IPhoneSimulatorDriver
RemoteWebDriver
SafariDriver
Q: Wait in selenium:
http://toolsqa.com/selenium-webdriver/implicit-explicit-n-fluent-wait/
import java.util.concurrent.TimeUnit; // used it for import wait class
1- Implicit Waits
2- Explicit Waits
3- Fluent Waits
1- ImplecitlyWaits
- 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.
- The default setting is 0.
- Once set, the implicit wait is set for the life of the Web Driver object instance until it changed again. This means that we can tell Selenium that we would like it to wait for a certain amount of time before throwing an exception that if it cannot find the element on the page.
- Implicit wait can accept the time amount in seconds,milliseconds, nanoseconds,minute etc. It depends on your requirement.
Syntax: driver.manage().timeouts().implecitlyWait(10, TimeUnits.SECONDS);
2. Explicit Wait:
- This wait gives you the options to wait until a desired condition is satisfied. You can use some of prebuilt ExpectedConditions for the elements to be visible, invisible,clickable etc.
-Syntax:
WebDriverWait wait = new WebDriverWait(driver, 10); //Explicit wait for 10 seconds
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("xpathlink")));
driver.get("http://www.gmail.com");
--> Explicit wait Expected Conditions List
alertIsPresent()
elementSelectionStateToBe()
elementToBeClickable()
elementToBeSelected()
frameToBeAvaliableAndSwitchToIt()
invisibilityOfTheElementLocated()
invisibilityOfElementWithText()
presenceOfAllElementsLocatedBy()
presenceOfElementLocated()
textToBePresentInElement()
textToBePresentInElementLocated()
textToBePresentInElementValue()
titleIs()
titleContains()
visibilityOf()
visibilityOfAllElements()
visibilityOfAllElementsLocatedBy()
visibilityOfElementLocated()
1- elementToBeClickable()
2- textToBePresentInElement()
3- alertIsPresent()
- wait.until(ExpectedConditions.alertIsPresent()) !=null);
4- titleIs()
- wait.until(ExpectedConditions.titleIs(“gmail”));
5- frameToBeAvailableAndSwitchToIt()
- wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“newframe”)));
6-
7-
8-
9-
10-
Q: Working with WebList[Drop Down List] in Selenium:
- http://testingpool.com/wp-content/uploads/2015/08/DemoApplication.html
- http://testingpool.com/working-with-weblist-in-selenium/
- Let’s understand different operation on weblist with examples.
- For performing operations on WebList, we use the Select class in selenium. We will look into some useful methods.
- 1 selectByVisibleText()
- 2 selectByIndex()
- 3 selectByValue()
- 4 deselectByVisibleText()
- 5 getOptions()
- Example of selectByVisibleText(): This method select the value in drop down by using the visible text. In our application, we have one drop down where we can select the numbers. In the code below, we are selecting number 4.
Weblist using selenium
Code for selecting the number 4: dropdownlist have 1 to 5 options
Selecting no. 4 in drop downJava
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class WebListExample {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/DemoApplication.html");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement source = driver.findElement(By.xpath("//select[@name='number']"));
//use select class to work on the weblist items
Select list = new Select(source);
list.selectByVisibleText("4"); //select number 4
list.selectByIndex("2"); //select second element option (Index start by 0 and first option is select element)
list.selectByValue("3"); //select third element option when display 3 as option text
list.deselectByVisibleText("5"); // deselect 5 text from list
}
}
- Similar way , we have more methods for deselecting.
- deselectAll(): It will deselect all the selected values in the list.
- deselectByIndex(index) : It will deselect on the basis of index as we have done with selectByIndex.
- deselectByValue(String value): It will deselect the list item on the basis of Value of the list.
- How to read all values of a webList?
We can read all the values in a weblist by using method getOptions(). This method will return the List of webelements and then in a for loop we can read the text property of all the webelements.
getOptions() exampleJava
public class WebListExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/DemoApplication.html");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement source = driver.findElement(By.xpath("//select[@name='Week']")); //multiple value list
//use select class to work on the weblist items
Select list = new Select(source);
List elements = list.getOptions();
for(WebElement item : elements){
System.out.println("List Item : "+item.getText()); //
}
}
}
Q: Working with CheckBoxes and Radio Buttons:
- Same code as click on checkbox/ radio button
Q: Select random value in the Weblist:
- Random ran = new Random();
int index= ran.nextInt(5); //it give random value b/w 0-4
// use index as index value from ddl list
Q: Work with multiple browser PopUp windows:
-
Q: Handle cookies in Selenium WebDriver:
- What is a cookie?
Cookies are small text files which gets stored with browser’s directory. When we open any website in a browser, then cookie is used to keep track of the movements in the site, guide us to resume where we it was left off, other customization function, remember registered login, theme selection etc.
Selenium provides methods to add or delete cookies. Let’s understand with examples.
1. getCookies(): This helps to fetch all the cookies available in the website. It will give a set (collection) of cookies, which you can iterate over to see its details.
Code to display all the cookies available in Facebook WebSite:
public class getCookiesExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");
Set cookie = driver.manage().getCookies();
for(Cookie c : cookie){
System.out.println(c);
}
}
}
Cookie usually stores the following information:
– The name of cookie.
– The value of the cookie.
– Domain the cookie is valid for.
– The expiration date of the cookie.
– The path the cookie is valid for.Web pages outside of that path cannot use the cookie.
2. addCookie(): This method helps you to add the cookie into the existing cookies. Cookie can be added in a pair of String Key and value.If the cookie’s domain name is left blank, it is assumed that the cookie is meant for the domain of the current document.
Syntax: Syntax:driver.manage().addCookie(arg0);
In the below example, we are adding cookie with String “This is my cookie.” and value “12345“.
public class getCookiesExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");
Cookie name = new Cookie("This is my cookie.", "123456");
driver.manage().addCookie(name);
Set cookie = driver.manage().getCookies();
for(Cookie c : cookie){
System.out.println(c);
}
}
}
Output:
This is my cookie.=123456; path=/; domain=www.facebook.com _js_reg_fb_gate=https%3A%2F%2Fwww.facebook.com%2F; path=/; domain=.facebook.com _js_reg_fb_ref=https%3A%2F%2Fwww.facebook.com%2F; path=/; domain=.facebook.com wd=1280×693; path=/; domain=.facebook.com _js_datr=ZkDSVZ8Fn5wuHTrdRxjDFRaS; expires=Mon, 02 Apr 2063 09:56:54 IST; path=/; domain=.facebook.com reg_ext_ref=; path=/; domain=.facebook.com
3. deleteCookieNamed(): Need to provide the name of the cookie which needs to be deleted. In te above cookie output , we have one cookie “_js_reg_fb_gate”. Let’s observe the output.
public class getCookiesExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");
Cookie name = new Cookie("This is my cookie.", "123456");
driver.manage().addCookie(name);
driver.manage().deleteCookieNamed("_js_reg_fb_gate");
Set cookie = driver.manage().getCookies();
for(Cookie c : cookie){
System.out.println(c);
}
}
}
This is my cookie.=123456; path=/; domain=www.facebook.com
_js_reg_fb_ref=https%3A%2F%2Fwww.facebook.com%2F; path=/; domain=.facebook.com
wd=1280×693; path=/; domain=.facebook.com
_js_datr=Y0PSVQtDszsr0zGAz9N-hQsB; expires=Mon, 02 Apr 2063 10:22:24 IST; path=/; domain=.facebook.com
reg_ext_ref=; path=/; domain=.facebook.com
Specified cookie has been deleted in the output.
4. deleteAllCookies(): It will delete all the cookies available in the Website. Let’s observe in the program.
public class getCookiesExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://facebook.com");
Cookie name = new Cookie("This is my cookie.", "123456");
driver.manage().addCookie(name);
driver.manage().deleteAllCookies();
Set cookie = driver.manage().getCookies();
for(Cookie c : cookie){
System.out.println(c);
}
}
}
Output: All cookies will be deleted
Q: Handling different type of pop ups in Selenium WebDriver:
- Confirm Box
- Alert Box
- Prompt Box
There can be 2 functionalities , either we can click on OK button or Cancel button. Let’s see how to handle this in selenium.
Command to click on OK button:
driver.switchTo().alert().accept();
After clicking on the OK button, it returns the massage ‘Confirmed.‘.
public class PopUpExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/AlertHandles.html");
//Click on the confirm box
WebElement ConfirmBox = driver.findElement(By.xpath("//*[@id='btnConfirm']"));
ConfirmBox.click();
// Click on OK button
driver.switchTo().alert().accept();
}
}
- Confirm box in selenium
Command to click on Cancel button:
driver.switchTo().alert().dismiss();
After clicking on the OK button, it returns the massage ‘Rejected.‘.
public class PopUpExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/AlertHandles.html");
//Click on the confirm box
WebElement ConfirmBox = driver.findElement(By.xpath("//*[@id='btnConfirm']"));
ConfirmBox.click();
// Click on Cancel button
driver.switchTo().alert().dismiss();
}
}
2. Show Alert:
As shown in figure 1.0, If you click on the button ‘Show alert’. It displays a pop up with a OK button.
Alert box with selenium
Command to Click on OK button in alert box:
driver.switchTo().alert().accept();
After clicking on the OK button, it returns the massage “Alert is gone.”.
Code for clicking OK button:
public class PopUpExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/AlertHandles.html");
//Click on the Alert box
WebElement AlertBox = driver.findElement(By.xpath("//*[@id='btnAlert']"));
AlertBox.click();
// Click on OK button
driver.switchTo().alert().accept();
}
}
Output:
Alert box handling in selenium
3. Prompt Box:
As shown in figure 1.0, If you click on the button ‘Show Prompt’. It displays a pop up with a edit box along with OK and cancel button.
You can enter the desired text under the Edit box and click OK. The same text will be displayed at the page.
Prompt box
Command to enter text and Click on OK button:
driver.switchTo().alert().sendKeys(“Learning Selenium”);
driver.switchTo().alert().accept();
Code to work with Prompt box:
public class PopUpExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/AlertHandles.html");
//Click on the Alert box
WebElement PromptBox = driver.findElement(By.xpath("//*[@id='btnPrompt']"));
PromptBox.click();
// Enter data
driver.switchTo().alert().sendKeys("Learning Selenium");
driver.switchTo().alert().accept();
}
}
Q: Working with WebTables in Selenium
- In the previous post, we have seen how to work with the different kind of Pop-ups in Selenium.In this post,we will see the working with WebTables in Selenium
WebTable is a very common feature you will find almost in every application. It contains a combination of rows and columns. Sometimes, there are requirements like you need to read the data from the webtables and use it as an output for some other functions , verify that data is correctly populated or not in the webtables etc.
We will take the example of a Webtable present in the the ‘www.testingpool.com‘. You can access this webtable at “http://testingpool.com/data-types-in-java/“.
This webtable displays the information about different data types in java.
webtable handling in selenium
WebTable
In WebTable , we can perform operations like counting total no. of rows, counting total no. of columns, extracting data etc. Let’s understand this with examples.
In HTML , Table is created by using the below commonly used tags (Explained only those tags used in our demo table.)
table: represent table
tbody: represent table body
tr: table row
td: table column
- Don't Forget Note Means Important Remember Forgetting
1 tr tag(rows) can have multiple td tags(columns).
- How to count no. of rows in a WebTable?
XPATH to count no. of rows:
//div[@class=’su-table’]/table/tbody/tr
As you can see in the below figure, this xpath returns total 9 rows.
Count no. of rows in webtable selenium
- How to count no. of columns in a WebTable?
//div[@class=’su-table’]/table/tbody/tr[1]/td
As you can see in the below figure, this xpath returns total 4 colums.
Coulmn count i a webtable selenium
Extract the data from the WebTable:
For extracting the data from WebTable, we will count no. of rows and columns. Then, we create nested for loop by using no. of rows and columns and use the method ‘getText()’ to extract the data.
public class WebTableExample {
private static WebDriver driver;
public static void main(String[] args) throws InterruptedException {
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/data-types-in-java/");
//count rows
List Rows = driver.findElements(By.xpath("//div[@class='su-table']/table/tbody/tr"));
int totalRows = Rows.size();
System.out.println(" Total rows : "+totalRows);
//count columns
List Columns = driver.findElements(By.xpath("//div[@class='su-table']/table/tbody/tr[1]/td"));
int totalColumns = Columns.size();
System.out.println(" Total Columns : "+totalColumns);
//Extract data
for(int i=1;i<=totalRows;i++){
for(int j=1;j<=totalColumns;j++){
WebElement dataCell = driver.findElement(By.xpath("//div[@class='su-table']/table/tbody/tr["+i+"]/td["+j+"]"));
System.out.println(dataCell.getText());
}
}
}
}
Output:
Total rows : 9
Total Columns : 4
Datatype Description Example Default value
byte Can be used for saving memory in large arrays.It is four times smaller than an int. byte a =100 0 short Can be used for saving memory in large arrays.It is two times smaller than an int. short x=1000 0 int int is generally use as default data type,unless there is memory concern int x=1000 0 long It is used when larger value than int is needed. int x=100000L 0L float use it if needs to save memory in large arrays of floating point numbers. int x=176.8f 0.0f double It is generally used as default value for decimal values. int d=176.8 0.0d boolean Its 2 possible value are – true and false. boolean name=true false char Char data type is used to store any character. char c =”A” ‘\u0000?
Q: Create Object Repository using Properties file:
- http://testingpool.com/create-object-repository-using-properties-file/
- This object repository will store all the information about the elements available in our application.
- The data will be stored in the form of key and value pair. This key can be read in the code to fetch the value associated with it.
- This key can be any kind of locator like XPATH, CSS, id , name etc and the value will its attribute value like XPATH Expression, CSS expression, id value of the element etc.
- You can keep it in any package or desired location as per your need. Let’s see how to use it in selenium.
- Step#1 We have created a package named as ‘com.resources’. Right click on this package and select a new File as shown in the figure below.
Create Properties
- Step#2 You can give any name to the file and save it with .properties extension.After that click on Finish button.(refer the below figure for understanding). We have given the name ‘OR.properties‘.
Properties file Saving Selenium
- Step#3: You can edit this file and provide object details with different locators like Xpath, id etc. We have saved the details of objects(elements) present on our demo site. We have stored the first name, last name, radio buttons, links etc. Refer the below figure to see how to add the objects.
Object repository in selenium
- Step#4 Create a class file, where we will write the code to use the properties file. Use the below code to understand the usage of properties file in Selenium.
In this code, we are reading the XPATH for ‘First Name’ and ‘Last Name’ from the properties file. Then we are using, those keys to find elements and enter the data into them.
public class PropExample {
private static WebDriver driver;
public static void main(String[] args) throws IOException {
// Create the file instance using the path where file stored
FileInputStream file = new FileInputStream(System.getProperty("user.dir")+"\\src\\com\\resources\\OR.properties");
Properties prop = new Properties();
prop.load(file); //Load the properties file
//Print the value of xpath stored in OR.properties
System.out.println(prop.getProperty("FirstName_xpath"));
System.out.println(prop.getProperty("Last_Name_xpath"));
driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://testingpool.com/wp-content/uploads/2015/08/DemoApplication.html");
//enter the first name and last name
// pick the object property from OR.properties file
driver.findElement(By.xpath(prop.getProperty("FirstName_xpath"))).sendKeys("Shekhar");
driver.findElement(By.xpath(prop.getProperty("Last_Name_xpath"))).sendKeys("Sharma");
}
}
Output:
//*[@id=’firstname’] //*[@id=’lastname’]
Read properties file in selenium
Advantage of using Properties file as object repository:
If we use properties file, then all the objects will be at common place. Suppose, If there is any change in any of the object property like xpath, id etc. and if that xpath has been hard coded in multiple test cases. Then ,we have to update each and every test case class file.
But if xpath is placed in properties file, then we have to update the changed xpath value only in at one place i.e. properties file. This properties file will be associated as object repository with all multiple test cases.
Q: How can read data from excel file:
- We can use following API to read/ write excel file
1- JExcel API
2- Apache POI API
1:- JExcel API
package mainCode;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.openqa.selenium.*;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import org.openqa.selenium.chrome.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import jxl.Sheet;
import jxl.Cell;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class ReadExcelFile {
public WebDriver driver;
public WebDriverWait wait;
@BeforeTest
public void beforeTest() {
try{
System.setProperty("webdriver.chrome.driver", "/home/adhran/Application/chromedriver");
// driver = new ChromeDriver();
// driver.get("https://www.freepdfconvert.com/pdf-word");
// driver.manage().timeouts().implicitlyWait(500, TimeUnit.SECONDS);
// driver.manage().window().maximize();
// wait= new WebDriverWait(driver,10);
}
catch(Exception e){
System.out.println(e+" : Error Occures!!! please check your code...");
}
}
@Test (enabled= true)
public void readExcelFile() throws IOException, InterruptedException, BiffException {
System.out.println("\nExcel File Read function executing ..\n");
Thread.sleep(5000);
File file= new File("/home/adhran/workspace/WebDriverTest/files/AdminCredentials.xlsx");
String filePath ="/home/adhran/workspace/WebDriverTest/files/AdminCredentials.xlsx";
try{
FileInputStream ifile= new FileInputStream(filePath);
Workbook wb = Workbook.getWorkbook(ifile);
Sheet st= wb.getSheet(0);
int noOfRows= st.getRows();
int noOfColumns= st.getColumns();
System.out.println("No of Rows and columns in file: "+ noOfRows +" , "+ noOfColumns);
System.out.println("All Data in sheet : ");
// to get all column value from excel file
for(int row =0; row< noOfRows; row++){
for(int col=0; col< noOfColumns ; col++){
System.out.println( st.getCell(col, row).getContents()+ "\t");
}
}
// to get single column value from excel file
Cell cl = st.getCell(0,0);
String data1= cl.getContents();
System.out.println("Sheet Data is : " + data1);
} catch(Exception e){
System.out.println(e + " :- Error Found!");
}
Thread.sleep(5000);
}
@Test(enabled= false)
public void getPropertyData() throws IOException {
// for windows
//FileInputStream file= new FileInputStrean(System.getProperty("user.dir")+ "\\src\\com\\resources\\OR.properties");
// linux
FileInputStream file= new FileInputStream("/home/adhran/workspace/WebDriverTest/src/test/resources/data.properties");
Properties prop= new Properties();
prop.load(file);
String fname= prop.getProperty("fname");
String lname= prop.getProperty("lname");
System.out.println("My Name is: " + fname + " "+lname);
}
@AfterTest
public void afterTest() {
driver.quit();
}
}
2:- Apache POI
To work on Excel, we have 2 types of pure java implementations of POI APIs.
- POI HSSF (.Xls)
- POI XSSF (.Xlsx)
- http://testingpool.com/wp-content/uploads/2015/08/HSSF-and-XSSF.png
POI-HSSF is used to work with Excel ’97(-2007) file format i.e XLS and POI -XSSF is used to work with Excel 2007 OOXML (.xlsx) file format(and later version).
xls | Xlsx
----------------------------------------------------
HSSFWorkbook Workbook XSSFWorkbook
HSSFSheet Sheet XSSFSheet
HSSFCell Cell XSSFCell
HSSFRow Row XSSFRow
- Write Data in Excel file using POI
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadWriteExcelFile {
public static void readXLSFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xls");
HSSFWorkbook wb = new HSSFWorkbook(ExcelFileToRead);
HSSFSheet sheet=wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(HSSFCell) cells.next();
if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
public static void writeXLSFile() throws IOException {
String excelFileName = "C:/Test.xls";//name of excel file
String sheetName = "Sheet1";//name of sheet
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
HSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
HSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
public static void readXLSXFile() throws IOException
{
InputStream ExcelFileToRead = new FileInputStream("C:/Test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFWorkbook test = new XSSFWorkbook();
XSSFSheet sheet = wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
//U Can Handel Boolean, Formula, Errors
}
}
System.out.println();
}
}
public static void writeXLSXFile() throws IOException {
String excelFileName = "C:/Test.xlsx";//name of excel file
String sheetName = "Sheet1";//name of sheet
XSSFWorkbook wb = new XSSFWorkbook();
XSSFSheet sheet = wb.createSheet(sheetName) ;
//iterating r number of rows
for (int r=0;r < 5; r++ )
{
XSSFRow row = sheet.createRow(r);
//iterating c number of columns
for (int c=0;c < 5; c++ )
{
XSSFCell cell = row.createCell(c);
cell.setCellValue("Cell "+r+" "+c);
}
}
FileOutputStream fileOut = new FileOutputStream(excelFileName);
//write this workbook to an Outputstream.
wb.write(fileOut);
fileOut.flush();
fileOut.close();
}
public static void main(String[] args) throws IOException {
writeXLSFile();
readXLSFile();
writeXLSXFile();
readXLSXFile();
}
}
- Writing to Excel File using POI API
In the previous post, we have given the overview of Apache POI API like what are these, how to download them etc.In this post, we will learn how to use POI API to write the data into Excel Files.
We will be using (.xlsx) format, for which we require implementation of XSSF API. Let’s understand the procedure step by step.
- Step#1 It is assumed that you have downloaded required jars and uploaded to your class ( as shown in previous post). As we know, an excel workbook contains the components like workbook, sheet, rows and cells. In Selenium also , we need to do the same with the help of coding. First we will create the objects like XSSFWorkbook, XSSFSheet.XSSFRow,XSSFCell etc.
private static XSSFWorkbook workbook;
private static XSSFSheet sheet;
private static XSSFCell cell;
private static XSSFRow row;
- Step#2 First , we will create one Excel file instance and a sheet under this named as ‘Data’.
workbook = new XSSFWorkbook();
sheet = workbook.createSheet("Data");
- Step#3 We need some data which will be written into the excel sheet. We have created some dummy data with the help of 2 dimensional array of String type. This data , we will write into the Excel sheet. (You can have data according to your requirement).
String[][] data = new String[3][2];
data[0][0] = "Name";
data[0][1] = "City";
data[1][0] = "Shekhar";
data[1][1] = "Bangalore";
data[2][0] = "Manan";
data[2][1] = "Delhi";
- Step#4 We will count the no. of rows and columns need to be filled up with the data. For that, we will count the length of array.
int dataRows = data.length;
int dataColumn = data[1].length;
- Step#5 Next, we need to create the row and column to set the value into it. For that , we will use the methods mentioned below.
Syntax:
//Create row
Row row = sheet.createRow(RowNumber)
//Create Cell
cell cell row.createCell(CellNumber)
//Set value into the cell
cell.setCellValue(DataValue);
- Step#6 We will use FileOutputStream method to flush the data to the Excel file and File path will be provided in the arguments. We use the write method to write the data into Excel file mentioned in FileOutputStream.
After that close the file output steam.
FileOutputStream fileout = new FileOutputStream(new File("E:\\Excel Files\\Sample.xlsx"));
workbook.write(fileout);
fileout.close();
fileout.close();
Full Code to write the data into Excel Files:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WritingExcelExample {
private static XSSFWorkbook workbook;
private static XSSFSheet sheet;
private static XSSFCell cell;
private static XSSFRow row;
public static void main(String[] args) throws InvalidFormatException, IOException {
//Create Excel Instance
workbook = new XSSFWorkbook();
//Create Sheet named as Data
sheet = workbook.createSheet("Data");
//String array
String[][] data = new String[3][2];
data[0][0] = "Name";
data[0][1] = "City";
data[1][0] = "Shekhar";
data[1][1] = "Bangalore";
data[2][0] = "Manan";
data[2][1] = "Delhi";
//Row count array
int dataRows = data.length;
//Column count
int dataColumn = data[1].length;
//for loop for iterating over the data
for(int i=0;i<dataRows;i++){
row =sheet.createRow(i);
for(int j=0;j<dataColumn;j++){
String fillData = data[i][j];
System.out.println(fillData+"--");
cell = row.createCell(j);
//Set value into cell
cell.setCellValue(fillData);
}
}
//Writing data to created excel instance
FileOutputStream fileout = new FileOutputStream(new File("C:\\Users\\Shekar Sharma\\Documents\\Sample1.xlsx"));
workbook.write(fileout);
fileout.close();
}
}
Output:
-->
Working with Action Interface in Selenium
To perform Advanced User Interactions, like drag and drop, keyboard events; selenium came up with Action and Actions interface under a comprehensive API, named as Advanced User Interaction which facilitate user actions to be performed on a application. Thus users can use this API to simulate usage of keyboard or mouse events.
Learn Action class in Selenium
Lets do some Action in Selenium
Example:-
To double-click a control we have DoubleClick(), method of Actions Class.
To Send keyboard actions, we have SendKeys() ,method.(Equivalent to WebElement.sendKey(...))
Clicking the mouse button that brings up the contextual menu.we can use “ContextClick()”, method.
Package:-
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.interactions.Action;
Syntax:-
Actions oAction=new Actions(selenium);
oAction.contextClick(element).perform();
Methods of Action class selenium
Actions Class Methods
Explanation:-
We need to import above packages to access the action and actions class methods.Create the actions class object and access the range of available methods.
What about multiple mouse and keyboard actions?
In above case we simply performed one action on the element, incase we want to perform sequence of events on the same element, we can achieve same by using build method.
Code:-
Actions oAction=new Actions(selenium);
Actions moreActions = oAction
.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT)
.sendKeys(element,"selenium");
Action enterInCaps= moreActions.build();
enterInCaps.perform();
Scenarios:-
1.How to right click and open the application in new window.
Code:-
Actions oAction=new Actions(selenium);
oAction.contextClick(element).perform();
oAction.sendKeys("w").perform();
2.How to fetch tool tip of a control in Selenium .
Code:-
Actions oAction=new Actions(selenium);
oAction.clickAndHold(element).perform();
3.How to send text in capital letters into a text-box?
Code:-
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
public class ActionClass {
public static void main(String[] args) {
WebDriver selenium = new FirefoxDriver();
System.out.println("Launching Browser");
//Opening the URL
selenium.get("http://www.uftHelp.com");
//Implicit wait for the browser to launch
selenium.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Google Search Text-box
WebElement element =selenium.findElement(By.id("gsc-i-id1"));
//Creating action class object
Actions oAction=new Actions(selenium);
//Creating action collection to perform numerous methods on element
Actions moreActions = oAction
.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT) //for caps
.sendKeys(element,"selenium");
Action enterInCaps= moreActions.build();
enterInCaps.perform();
System.out.println("Text is entered in Captial letters");
//Closing the browser
//selenium.quit();
}
}
4.How we can drag and drop element in selenium?
Code:-
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class DragAndDrop {
public static void main(String[] args) {
WebDriver selenium = new FirefoxDriver();
System.out.println("Launching Browser");
//Opening the URL
selenium.get("http://jqueryui.com/resources/demos/droppable/default.html");
//Implicit wait for the browser to launch
selenium.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
//Identifying the elements to perform action
WebElement draggable = selenium.findElement(By.xpath("//*[@id='draggable']"));
WebElement droppable = selenium.findElement(By.xpath("//*[@id='droppable']"));
Actions oAction = new Actions(selenium);
//Performing Drag and Drop operation
oAction.dragAndDrop(draggable, droppable).perform();
System.out.println("Successfully completed the Drag-Drop operation");
}
}
Note:- we can also re-size the control, just need to change syntax a bit
oAction.dragAndDropBy(resize, 400, 200).perform();
5.How to refresh a application window using Action class?
Code:-
Actions oAction=new Actions(selenium);
oActions.keyDown(Keys.CONTROL).sendKeys(Keys.F5).perform();
Q:. Get domain name using java script executor
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String CurrentURLUsingJS=(String)javascript.executeScript("return document.domain");
Q: Generate alert using webdriver's java script executor interface
JavascriptExecutor javascript = (JavascriptExecutor) driver;
javascript.executeScript("alert('Test Case Execution Is started Now..');");
Q: Selecting or Deselecting value from drop down in selenium webdriver.
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
listbox.deselectAll();
Q: isMultiple()
-It will return true if select box is multiselect else it will return false.
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
boolean value = listbox.isMultiple();
@Test
public void test () throws InterruptedException
{
Select listbox = new Select(driver.findElement(By.xpath("//select[@name='FromLB']")));
//To verify that specific select box supports multiple select or not.
if(listbox.isMultiple())
{
System.out.print("Multiple selections is supported");
listbox.selectByVisibleText("USA");
listbox.selectByValue("Russia");
listbox.selectByIndex(5);
Thread.sleep(3000);
//To deselect all selected options.
listbox.deselectAll();
Thread.sleep(2000);
}
else
{
System.out.print("Not supported multiple selections");
}
}
Q: Navigate to URL or Back or Forward in Selenium Webdriver
driver.navigate().to("http://only-testing-blog.blogspot.com/2014/01/textbox.html");
driver.navigate().back();
driver.navigate().forward();
14. Verify Element Present in Selenium WebDriver
Boolean iselementpresent = driver.findElements(By.xpath("//input[@id='text2']")).size()!= 0;
15. Capturing entire page screenshot in Selenium WebDriver
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("D:\\screenshot.jpg"));
16. Generating Mouse Hover Event In WebDriver
Actions actions = new Actions(driver);
WebElement moveonmenu = driver.findElement(By.xpath("//div[@id='menu1']/div"));
actions.moveToElement(moveonmenu);
actions.perform()
17. Handling Multiple Windows In Selenium WebDriver.
Get All Window Handles.
Set AllWindowHandles = driver.getWindowHandles();
Extract parent and child window handle from all window handles.
String window1 = (String) AllWindowHandles.toArray()[0];
String window2 = (String) AllWindowHandles.toArray()[1];
Use window handle to switch from one window to other window.
driver.switchTo().window(window2);
18. Check Whether Element is Enabled Or Disabled In Selenium Web driver.
boolean fname = driver.findElement(By.xpath("//input[@name='fname']")).isEnabled();
System.out.print(fname);
19. Enable/Disable Textbox During Selenium Webdriver Test Case Execution.
JavascriptExecutor javascript = (JavascriptExecutor) driver;
String todisable = "document.getElementsByName('fname')[0].setAttribute('disabled', '');";
javascript.executeScript(todisable);
String toenable = "document.getElementsByName('lname')[0].removeAttribute('disabled');";
javascript.executeScript(toenable);
20. Selenium WebDriver Assertions With TestNG Framework
assertEquals
Assert.assertEquals(actual, expected);
assertNotEquals
Assert.assertNotEquals(actual, expected);
assertTrue
Assert.assertTrue(condition);
assertFalse
Assert.assertFalse(condition);
21. Submit() method to submit form
driver.findElement(By.xpath("//input[@name='Company']")).submit();
22. Handling Alert, Confirmation and Prompts Popups
String myalert = driver.switchTo().alert().getText();
driver.switchTo().alert().accept();
driver.switchTo().alert().dismiss();
driver.switchTo().alert().sendKeys("This Is John");
Q: WebDriver how to wait ?
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.alertIsPresent());
Q: How to wait till element visible or appear or present on page
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@id='text3']")));
Q: How to apply wait in webdriver till element becomes invisible or hidden?
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//input[@id='text4']")));
Q: Difference Between findElement and findElements with example?
findElement() method
- We need to use findElement method frequently in our webdriver software test case because this is the only way to locate any element in webdriver software testing tool.
- findElement method is useful to locating targeted single element.
- If targeted element is not found on the page then it will throw NoSuchElementException.
findElements() method
- We are using findElements method just occasionally.
- findElements method will return list of all the matching elements from current page as per given element locator mechanism.
- If not found any element on current page as per given element locator mechanism, it will return empty list.
@Test
public void test () throws InterruptedException
{
WebElement option = driver.findElement(By.xpath("//option[@id='country5']"));
System.out.print(option.getAttribute("id")+" - "+option.getText());
List options= driver.findElements(By.xpath("//option"));
System.out.println(options.size());
for(int i=0;i<=options.size();i++)
{
String str = options.get(i).getAttribute("id")+" - "+options.get(i).getText();
System.out.println(str);
}
}
Q: How To Get/Extract All Links From Web Page Using Selenium WebDriver?
@Test
public void test () throws InterruptedException
{
try {
List no = driver.findElements(By.tagName("a"));
int nooflinks = no.size();
System.out.println(nooflinks);
for (WebElement pagelink : no)
{
String linktext = pagelink.getText();
String link = pagelink.getAttribute("href");
System.out.println(linktext+" ->");
System.out.println(link);
}
}catch (Exception e){
System.out.println("error "+e);
}
}
Q: How To Handle Dynamic Web Table In Selenium WebDriver?
@Test
public void Handle_Dynamic_Webtable() {
//To locate table.
WebElement mytable = driver.findElement(By.xpath(".//*[@id='post-body-8228718889842861683']/div[1]/table/tbody"));
//To locate rows of table.
List rows_table = mytable.findElements(By.tagName("tr"));
//To calculate no of rows In table.
int rows_count = rows_table.size();
//Loop will execute till the last row of table.
for (int row=0; row<rows_count; row++){
//To locate columns(cells) of that specific row.
List Columns_row = rows_table.get(row).findElements(By.tagName("td"));
//To calculate no of columns(cells) In that specific row.
int columns_count = Columns_row.size();
System.out.println("Number of cells In Row "+row+" are "+columns_count);
//Loop will execute till the last cell of that specific row.
for (int column=0; column<columns_count; column++){
//To retrieve text from that specific cell.
String celtext = Columns_row.get(column).getText();
System.out.println("Cell Value Of row number "+row+" and column number "+column+" Is "+celtext);
}
System.out.println("--------------------------------------------------");
}
}
Q: Read-Write Text File In Java - Tutorials For WebDriver?
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class RW_File {
public static void main(String[] args) throws IOException {
//Create File In D: Driver.
String TestFile = "D:\\temp.txt";
File FC = new File(TestFile);//Created object of java File class.
FC.createNewFile();//Create file.
//Writing In to file.
//Create Object of java FileWriter and BufferedWriter class.
FileWriter FW = new FileWriter(TestFile);
BufferedWriter BW = new BufferedWriter(FW);
BW.write("This Is First Line."); //Writing In To File.
BW.newLine();//To write next string on new line.
BW.write("This Is Second Line."); //Writing In To File.
BW.close();
//Reading from file.
//Create Object of java FileReader and BufferedReader class.
FileReader FR = new FileReader(TestFile);
BufferedReader BR = new BufferedReader(FR);
String Content = "";
//Loop to read all lines one by one from file and print It.
while((Content = BR.readLine())!= null){
System.out.println(Content);
}
}
}
Q: How To Extract Table Data/Read Table Data Using Selenium WebDriver Example?
package Testng_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class table {
WebDriver driver = new FirefoxDriver();
@BeforeTest
public void setup() throws Exception {
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2013/09/test.html");
}
@AfterTest
public void tearDown() throws Exception {
driver.quit();
}
@Test
public void print_data(){
//Get number of rows In table.
int Row_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr")).size();
System.out.println("Number Of Rows = "+Row_count);
//Get number of columns In table.
int Col_count = driver.findElements(By.xpath("//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[1]/td")).size();
System.out.println("Number Of Columns = "+Col_count);
//divided xpath In three parts to pass Row_count and Col_count values.
String first_part = "//*[@id='post-body-6522850981930750493']/div[1]/table/tbody/tr[";
String second_part = "]/td[";
String third_part = "]";
//Used for loop for number of rows.
for (int i=1; i<=Row_count; i++){
//Used for loop for number of columns.
for(int j=1; j<=Col_count; j++){
//Prepared final xpath of specific cell as per values of i and j.
String final_xpath = first_part+i+second_part+j+third_part;
//Will retrieve value from located cell and print It.
String Table_data = driver.findElement(By.xpath(final_xpath)).getText();
System.out.print(Table_data +" ");
}
System.out.println("");
System.out.println("");
}
}
}
Q: Diff b/w Junit and TestNG
Similarities Between JUnit and TestNG
- We can create test suite in JUnit and TestNG both frameworks.
- Timeout Test Is possible very easily in both the frameworks.
- We can ignore specific test case execution of software web application from suite in both the frameworks.
- It is possible to create expected exception test for software web application in both the frameworks.
- Annotations - Few annotations are similar in both frameworks suite like @Test, @BeforeClass, @AfterClass. JUnit's Annotations @Before and @After are similar to TestNG's @BeforeMethod and @AfterMethod annotations.
Difference Between JUnit and TestNG
- In TestNG, Parameterized test configuration is very easy while It is very hard to configure Parameterized test in JUnit.
- TestNG support group test but it is not supported in JUnit.
- TestNG has a feature to configure dependency test. Dependency test configuration for software web application is not possible in JUnit.
- TestNG support @BeforeTest, @AfterTest, @BeforeSuite, @AfterSuite, @BeforeGroups, @AfterGroups which are not supported in JUnit.
- Test prioritization, Parallel testing is possible in TestNG. It is not supported by JUnit.
View more features of TestNG @ THIS LINK .
Annotation in TestNG:
- Basic @Factory Example
- @Factory annotation provided by TestNG. @Factory allows tests to be created at runtime depending on certain data-sets or conditions.
- To run a set of tests with different data values. To achieve this we may define a separate set of tests inside a suite in the testng XML and test the required scenario.
- The problem with this approach is that, if you get an extra set of data, you will need to redefine the test.
- TestNG solves this problem by providing the @Factory annotation feature. Factory in TestNG defines and creates tests dynamically at runtime.
- TestNG factory class is used to create instance of testNg class at runtime (dynamically). When we apply Factory annotation on method, it always return object array of Object class ( “Object[]”). This is useful annotation when you run test multiple time.
- TestNG pick @Factory method from class and consider each object mentioned in factory test as a TestNg class and invoke in separate.
- http://howtodoinjava.com/testng/testng-factory-annotation-tutorial/
Example: FactoryClassImp.java
package com.tests;
import org.testng.annotations.Factory;
public class FactoryClassImp {
@Factory
public Object[] createTest() {
Object[] res = new Object[3];
res[0] = new FactoryTestClass(2, 2);
res[1] = new FactoryTestClass(2, 3);
res[2] = new FactoryTestClass(2, 4);
return res;
}
}
TestNg class file (TestNgTestClass.java)
package com.tests;
import org.testng.Assert;
import org.testng.annotations.Test;
public class TestNgTestClass {
int a;
int b;
public TestNgTestClass(int a, int b) {
this.a = a;
this.b = b;
}
@Test
public final void testEqual() {
Assert.assertEquals(a , b);
}
}
public class SimpleTest {
@Test
public void simpleTest() {
System.out.println("Simple Test Method.");
}
}
public class SimpleTestFactory {
@Factory
public Object[] factoryMethod() {
return new Object[] { new SimpleTest(), new SimpleTest() };
}
}
Using @DataProvider along with the @Factory annotation
The @DataProvider feature can also be used with the @Factory annotation for creating tests at runtime. This can be done by declaring the @Factory annotation on a constructor of a class or on a regular method.
public class DataProviderTest
{
private int param;
@Factory(dataProvider = "dataMethod")
public DataProviderTest(int param) {
this.param = param;
}
@DataProvider
public static Object[][] dataMethod() {
return new Object[][] { { 0 }, { 1 } };
}
@Test
public void testMethodOne() {
int opValue = param + 1;
System.out.println("Test method one output: " + opValue);
}
@Test
public void testMethodTwo() {
int opValue = param + 2;
System.out.println("Test method two output: " + opValue);
}
}
Q: Difference between @Factory and @DataProvider
Below is the main difference between @Factory and @DataProvider functionalities on TestNG.
DataProvider: A test method that uses DataProvider will be executed a multiple number of times based on the data provided by the DataProvider. The test method will be executed using the same instance of the test class to which the test method belongs.
Factory: A factory will execute all the test methods present inside a test class using a separate instance of the respective class.
Q17) --***********************************************
Type of Parameterization in TestNG-
This concept which we achieve by parameterization is called Data Driven Testing .
There are two ways by which we can achieve parameterization in TestNG
1- With the help of Parameters annotation and TestNG XML file.
@Parameters(({"name","passwd"}))
2- With the help of DataProvider annotation.
@DataProvider({name="getData"})
- DataProvider in TestNG
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.
The name of this data provider. If it's not supplied, the name of this data provider will automatically be set to the name of the method.
package mainCode;
import org.testng.annotations.Test;
import org.openqa.selenium.By;
import org.testng.annotations.*;
import org.openqa.selenium.WebDriver;
import java.io.IOException;
public class DataProviderWithExcelInput {
public WebDriver driver;
public WebDriverWait wait;
private By username = By.id("companyEmail");
private By password = By.id("password");
private By login = By.className("container");
@Test(dataProvider="getData")
public void displayData(String username, String password) throws IOException, InterruptedException {
System.out.println( "username : " +username + " & Password : " +password );
}
@DataProvider
public Object[][] getData(){
Object[][] data = new Object[3][2];
data[0][0] ="sampleuser1";
data[0][1] = "abcdef";
// 2nd row
data[1][0] ="testuser2";
data[1][1] = "zxcvb";
// 3rd row
data[2][0] ="guestuser3";
data[2][1] = "pass123";
return data;
}
}
- Passing data to DataProvider from Excel sheet: OR read data from excel file to login.
We will write a simple program in which we will validate login screen by taking multiple usernames and passwords. The annotated method must return object[][] where each object[] can be assigned to the test method one as username and the other parameter as password.
Step 1: First create a method to read excel data and return string array.
Step 2: Create before class and after class methods which helps in getting the browser and closing them when done.
Step 3: Create a data provider which actually gets the values by reading the excel.
Step 4: Create a Test which takes two parameters username and password.
Step 5: Add dataprovider name for @Test method to receive data from dataprovider.
package mainCode;
import org.testng.annotations.Test; import org.openqa.selenium.By;
import org.testng.annotations.*; import org.openqa.selenium.WebDriver; import java.io.IOException;
import java.util.concurrent.TimeUnit; import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterTest;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class DataProviderWithExcelInput {
public WebDriver driver;
public WebDriverWait wait;
private By user = By.id("Email");
private By next = By.id("next");
private By pass = By.id("Passwd");
private By login = By.id("signIn");
private By compose = By.xpath("//*[@id=':yo']/div/div");
@BeforeClass
public void setUp() throws IOException, InterruptedException{
driver = new FirefoxDriver();
driver.navigate().to("https://gmail.com/");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10,TimeUnit.SECONDS);
}
@Test(dataProvider="getData")
public void gmailLoginWithDataProvider(String username, String password) throws IOException, InterruptedException {
driver.findElement(user).clear();
driver.findElement(user).sendKeys(username);
driver.findElement(next).click();
driver.findElement(pass).clear();
driver.findElement(pass).sendKeys(password);
Thread.sleep(10000);
driver.findElement(login).click();
System.out.println( "username : " + username + " & Password : " + password );
Thread.sleep(100000);
}
@DataProvider
public Object[][] getData() throws IOException, InterruptedException {
// Object[][] loginData = new Object[1][2];
// loginData[0][0] = "pratap9011";
// loginData[0][1] = "mcaamity8087";
Object[][] loginData = readInputFromExcel("/home/adhran/workspace-java/WebDriverTest/files/AdminCredentials.xls","Sheet1");
return loginData;
}
public String[][] readInputFromExcel(String filePath, String sheetName) throws IOException, InterruptedException {
String[][] arrayExcelData = null;
try{
Workbook wb = Workbook.getWorkbook((new FileInputStream(filePath)));
Sheet sh = wb.getSheet(sheetName);
int noOfRows= sh.getRows();
int noOfCol = sh.getColumns();
System.out.println("Total no rows : " + noOfRows+ " & cols in "+ noOfCol+" in excel file");
arrayExcelData = new String[noOfRows-1][noOfCol];
for(int i=1;i< noOfRows; i++) {
for (int j=0; j < noOfCol; j++){
arrayExcelData[i-1][j]= sh.getCell(j,i).getContents();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
public void sleepWait(int time) throws IOException, InterruptedException {
Thread.sleep(time);
}
@AfterTest
public void afterTest() {
driver.quit();
}
}
Q19: Selenium Grid Example:
- Benefits of Selenium Grid:
- Selenium Grid gives the flexibility to distribute your test cases for execution.
- Reduces batch processing time.
- Can perform multi-browser testing.
- Can perform multi-OS testing.
Basic terminology of Selenium Grid:
- Hub: Hub is the central point to the entire GRID Architecture which receives all requests. There is only one hub in the selenium grid. Hub distributes the test cases across each node.
- Node: There can be multiple nodes in Grid. Tests will run in nodes. Each node communicates with the Hub and performs test assigned to it.
Steps:
- Step 1: Download Selenium Server jar file from Selenium’s official website.
- Step 2: 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
- Status can be checked by using the web interface: http://localhost:4444/grid/console
- Step 3: 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
Browser and Nodes: After starting hub and nodes on each machine when you will navigate to GRID Console
You will find 5 Chrome, 5 Firefox and 1 IE browser under Browser section like below.
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 -browser browserName=iexplore
- to configure multiple browser at same time:-
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=chrome
- maxInstances:
- 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
- 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
- use following code to run testNG script:
- 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();
}
}
- testNg.xml:
- to run parallel-
- Configuration using JSON file:
The grid can also be launched along with its configuration by using JSON configuration file.
Create a JSON file for having below configuration. Here I have created a JSON file named as grid_hub.json
{
"host": null,
"port": 4444,
"newSessionWaitTimeout": -1,
"servlets" : [],
"prioritizer": null,
"capabilityMatcher": "org.openqa.grid.internal.utils.DefaultCapabilityMatcher",
"throwOnCapabilityNotPresent": true,
"nodePolling": 5000,
"cleanUpCycle": 5000,
"timeout": 300000,
"maxSession": 5
}
- Start the hub using below command
java -jar selenium-server-standalone-2.41.0.jar -role hub –hubConfig grid_hub.json
Similarly, create different json file for different nodes as per required configuration.
Here is an example of JSON configuration file for node named as grid_node.json
{
"capabilities":
[
{
"browserName": "chrome",
"maxInstances": 2
},
{
"browserName": "firefox",
"maxInstances": 2
},
{
"browserName": "internet explorer",
"maxInstances": 1
}
],
"configuration":
{
"nodeTimeout":120,
"port":5555,
"hubPort":4444,
"hubHost":"localhost",
"nodePolling":2000,
"registerCycle":10000,
"register":true,
"cleanUpCycle":2000,
"timeout":30000,
"maxSession":5,
}
}
To start the node
java -jar selenium-server-standalone-2.41.0.jar -role rc –nodeConfig grid_node.json
You can change all the configuration of a browser, maxInstances, port, maxSession etc. in the JSON file.
You can provide browser version, platform in the JSON config file like below
{
“browserName”: “chrome”,”version”:”8”,”platform”:”Windows”
}
- Excecute with driver path of WebDriver:-
java -jar selenium-server-standalone-2.48.2.jar -role node -hub http://10.0.0.6:4444/grid/register -Dwebdriver.chrome.driver=.\chromedriver.exe
Q20: Selenium Cookies Actions:
-In Selenium Webdriver, we can query and interact with cookies with below built-in method:
- driver.manage().getCookies(); // Return The List of all Cookies
- driver.manage().getCookieNamed(arg0); //Return specific cookie according to name
- driver.manage().addCookie(arg0); //Create and add the cookie
- driver.manage().deleteCookie(arg0); // Delete specific cookie
- driver.manage().deleteCookieNamed(arg0); // Delete specific cookie according Name
- driver.manage().deleteAllCookies(); // Delete all cookies
- https://www.guru99.com/handling-cookies-selenium-webdriver.html
- FOLLOWING CODE IS TO WRITING COOKIES FILE FOR NEXT LOGIN
package CookieExample;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.Cookie;
public class cookieRead{
public static void main(String[] args)
{
WebDriver driver;
System.setProperty("webdriver.chrome.driver","G:///chromedriver.exe");
driver=new ChromeDriver();
driver.get("http://demo.guru99.com/test/cookie/selenium_aut.php");
// Input Email id and Password If you are already Register
driver.findElement(By.name("username")).sendKeys("abc123");
driver.findElement(By.name("password")).sendKeys("123xyz");
driver.findElement(By.name("submit")).click();
// create file named Cookies to store Login Information
File file = new File("Cookies.data");
try
{
// Delete old file if exists
file.delete();
file.createNewFile();
FileWriter fileWrite = new FileWriter(file);
BufferedWriter Bwrite = new BufferedWriter(fileWrite);
// loop for getting the cookie information
// loop for getting the cookie information
for(Cookie ck : driver.manage().getCookies())
{
Bwrite.write((ck.getName()+";"+ck.getValue()+";"+ck.getDomain()+";"+ck.getPath()+";"+ck.getExpiry()+";"+ck.isSecure()));
Bwrite.newLine();
}
Bwrite.close();
fileWrite.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
}
