Test NG Interview Question
Q) DesireCapabilities:
- 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);
Q) Robot Class Example in Selenium:
- import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
public class TestRobot {
private Robot robot;
private static final int SPEED = 300;
private void execute(int[] letter){
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
for (int i = 0;i robot.delay(SPEED);
robot.keyPress(letter[i]);
robot.keyRelease(letter[i]);
}
}
public static void main(String[] args) {
TestRobot t = new TestRobot();
int[] executeNotepad = {KeyEvent.VK_WINDOWS,KeyEvent.VK_N,KeyEvent.VK_O,KeyEvent.VK_T,KeyEvent.VK_E,KeyEvent.VK_P,KeyEvent.VK_A,KeyEvent.VK_D,KeyEvent.VK_ENTER};
int[] maximizeIt = {KeyEvent.VK_ALT, KeyEvent.VK_SPACE, KeyEvent.VK_UP, KeyEvent.VK_UP, KeyEvent.VK_ENTER};
int[] messageToPrint = {KeyEvent.VK_H,KeyEvent.VK_E,KeyEvent.VK_L,KeyEvent.VK_L,KeyEvent.VK_O};
t.execute(executeNotepad);
t.execute(maximizeIt);
t.execute(messageToPrint);
}
}
Q) What is the use of @Test(invocationCount=x)?
- The invocationcount attribute tells how many times TestNG should run a test method
@Test(invocationCount = 10)
public void testCase1(){
In this example, the method testCase1 will be invoked ten times
Q) What is the use of @Test(threadPoolSize=x)?
- The threadPoolSize attribute tells to form a thread pool to run the test method through multiple threads.
Note: This attribute is ignored if invocationCount is not specified
@Test(threadPoolSize = 3, invocationCount = 10)
public void testCase1(){}
In this example, the method testCase1 will be invoked from three different threads
--********************************************************************************
TestNG Introduction
TestNG is a unit test framework designed for testing needs (developers / Test Engineers). It is inspired from JUnit by adding new functionalities which made TestNG more powerful than other unit test frameworks.
We can use TestNG for the below reasons:
1. To Run test cases in the order which we provide
2. We can run classes without using Main method.
2. To generate reports
3. To read the data from Excel file.
In Eclipse, it is very easy to Install TestNG Software, In the latest version, you will find an option to install software / Market place. Simple search for TestNG which will display a link to install. Click on Install. Installation will get completed in a short time.
Click here to install TestNG in Eclipse
The below are the different annotations available in TestNG
@BeforeSuite: This annotation method will execute before all tests in this suite
@AfterSuite:This annotation method will execute after all tests in this suite
@BeforeTest: This annotation method will execute before any test method belonging to the classes inside the Test tag is executed.
@AfterTest: This annotation method will execute after all the test methods belonging to the classes inside the Test tag have executed.
@BeforeGroups: The list of groups that this configuration method will execute before. This method is guaranteed to execute shortly before the first test method that belongs to any of these groups is invoked.
@AfterGroups: The list of groups that this configuration method will execute after. This method is guaranteed to execute shortly after the last test method that belongs to any of these groups is invoked.
BeforeClass: This annotation method will execute before the first test method in the current class is invoked.
@AfterClass: This annotation method will execute after all the test methods in the current class have been executed.
@BeforeMethod: This annotation method will execute before each test method.
@AfterMethod:The annotated method will be executed after each test method.
Below is the basic Example program using the above annotations:
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class TesNGExample {
@BeforeTest
public void openDBConnection(){
System.out.println("I will execute Before any Test method/case executes");
}
@AfterTest
public void CloseDBConnection(){
System.out.println("I will execute After all Test method/case executes");
}
@Test
public void testCase01(){
System.out.println("Im in first testcase");
}
@Test
public void testCase02(){
System.out.println("Im in second testcase");
}
@BeforeMethod
public void openBrowser(){
System.out.println("I will be executed before Each Test Method");
}
@AfterMethod
public void CloseBrowser(){
System.out.println("I will be executed After Each Test Method");
}
}
Below is the Output :
I will execute Before any Test method/case executes
I will be executed before Each Test Method
Im in first testcase
I will be executed After Each Test Method
I will be executed before Each Test Method
Im in second testcase
I will be executed After Each Test Method
I will be executed before Each Test Method
Im in third testcase
I will be executed After Each Test Method
I will execute After all Test method/case executes
PASSED: testCase01
PASSED: testCase02
PASSED: testCase03
Q)
--***************************************************
Q) TestNG XML example to execute with package names:-
- It will exceute all classes which have TestNG Annotations.
- http://www.seleniumeasy.com/testng-tutorials/testngxml-example-to-execute-with-package-names
Q) TestNG XML example to execute Multiple Classes:
-
Q) Grouping in TestNG:
- Suite Class Code:
@Test(groups="Regression")
public void testCaseOne(){
System.out.println("Im in testCaseOne - And in Regression Group");
}
@Test(groups="Regression")
public void testCaseTwo(){
System.out.println("Im in testCaseTwo - And in Regression Group");
}
@Test(groups="Smoke Test")
public void testCaseThree(){
System.out.println("Im in testCaseThree - And in Smoke Test Group");
}
@Test(groups="Regression")
public void testCaseFour(){
System.out.println("Im in testCaseFour - And in Regression Group");
}
- TestNG XML file
Q) TestNG include/ exclude groups in testng.xml file:
- - TestNG XML file
Q) Exception Test in TestNG:
- In TestNG we use expectedException with @Test annotation and we need to specify the type of exceptions that are expected to be thrown when executing the test methods.
import org.testng.annotations.Test;
public class TestNGExamples {
@Test(expectedExceptions=ArithmeticException.class)
public void dividedByZeroExample1(){
int e = 1/0;
}
@Test
public void dividedByZeroExample2(){
int e = 1/0;
}
}
- Output:
- dividedByZeroExample1 : Passed
- dividedByZeroExample2 : Failed
Q) Skip Exception Test in TestNG:
- Using TestNG, we have multiple ways to Skip a test based on our requirement. We can Skip complete test without executing it or we can Skip a test when a specific condition is not satisfied.
1 - @Test(enabled=false) annotation is used to skip a test case if it is not ready to test. We don't need to import any additional statements.
2 - throw new SkipException("Your message");
- And we can also perform a CONDITIONAL Skip, i.e.. We can have a condition to check and then SKIP test if condition is not satisfied. For Example, if there is no data available to perform a test, we can skip the test instead of making that test as failed.
- package packOne;
import org.testng.SkipException;
import org.testng.annotations.Test;
public class SkipExample {
@Test(enabled=false)
public void testCaseEnabling(){
System.out.println("I'm Not Ready, please don't execute me");
}
@Test
public void testCaseSkipException(){
System.out.println("Im in skip exception");
throw new SkipException("Skipping this exception");
}
@Test
public void testCaseConditionalSkipException(){
System.out.println("Im in Conditional Skip");
if(!DataAvailable)
throw new SkipException("Skipping this exception");
System.out.println("Executed Successfully");
}
}
Q) Excecute Parallel Tests, Classes, Methods in TestNG.xml:
-
--***********************************************
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();
}
}
Q
--********************************************************************************************
--************************ Selenium Questions with coding ***********************************
--********************************************************************************************
Q) How to right click on element and hit enter... When we don't have submit or select button?
-Action action = new Action(driver);
action.moveToElement(Element).contextClick().sendKeys(Keys.ENTER).build().perform();
Q) Get Table Text for first row only
-Below code helps me to check out a table from my search results on the web page and get its text.
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class WebTableExample {
public static void main(String[] args) {
WebDriver driver = new InternetExplorerDriver();
driver.get("http://localhost/test/test.html");
WebElement table_element = driver.findElement(By.id("testTable"));
List tr_collection=driver.findElements(By.xpath("id('testTable')/tbody/tr"));
System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
int row_num,col_num;
row_num=1;
for(WebElement trElement : tr_collection){
List td_collection=trElement.findElements(By.xpath("td"));
System.out.println("NUMBER OF COLUMNS="+td_collection.size());
col_num=1;
for(WebElement tdElement : td_collection){
System.out.println("row # "+row_num+", col # "+col_num+ "text="+tdElement.getText());
col_num++;
}
row_num++;
}
}
}
Q) How to wait for Loading Spinner complete its process?
-ex:
WebDriverWait wait = new WebDriverWait(driver, lets say 1 hour);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));
OR
List elem = driver.findElements(By.xpath("//div[@class='k-loading-mask']"));
while(elem.size() > 0)
{
elem = driver.findElements(By.xpath("//div[@class='k-loading-mask']"));
}
OR
driver.get("http://jsfiddle.net/nwinkler/Fe69G/");
driver.switchTo().frame("result");
WebElement refreshElem = driver.findElement(By.xpath("/html/body/div/div[1]/div/a[1]"));
refreshElem.click();
while(true)
{
List elem = driver.findElements(By.xpath("//div[@class='k-loading-mask']"));
if(elem.size() > 0)
System.out.println("found");
}
Note: -Some WebDriver Tips & Tricks.
To open your site on the specific language.
For Firefox:
FirefoxProfile firefoxProfile= new FirefoxProfile();
firefoxProfile.setPreference("intl.accept_languages", "de");
Webdriver driver = new FirefoxDriver(firefoxProfile);
driver.get("https://google.com") ;
It opens in German.
For chrome:
ChromeOptions options = new ChromeOptions();
options.addArguments("--lang=de");
driver = new ChromeDriver(options);
To learn more about chromedriver options go to https://www.linkedin.com/pulse/command-line-switches-chrome-driver-evgeny-tkachenko-6024124673334214656?trk=prof-post
Starts the browser maximized, regardless of any previous settings:
ChromeOptions options = new ChromeOptions();
options.addArguments("--start-maximized");
driver = new ChromeDriver(options);
To open a browser with extensions:
For chrome:
ChromeOptions options = new ChromeOptions();
options.addExtensions(new File("src\\test\\resources\\extensions\\extension.crx"));
driver = new ChromeDriver(options);
To start the Firefox with the firebug:
FirefoxProfile firefoxProfile= new FirefoxProfile();
firefoxProfile.addExtension(
new File("src\\test\\resources\\extensions\\firebug-2.0.6.xpi"));
firefoxProfile.setPreference("extensions.firebug.currentVersion",versionFirebug); // Avoid startup screen
Webdriver driver = new FirefoxDriver(firefoxProfile);
To allow launching the plugin:
FirefoxProfile firefoxProfile= new FirefoxProfile();
firefoxProfile.setPreference("plugin.state.flash", 2);
Webdriver driver = new FirefoxDriver(firefoxProfile);
To download file to specified location:
FirefoxProfile firefoxProfile= new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList",2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting",False);
firefoxProfile.setPreference("browser.download.dir",'YOUR_PATH');
firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
WebDriver driver= new FirefoxDriver(firefoxProfile);
To open url in new window
public void openNewWindow(String url) {
Set windowHandles = driver.getWindowHandles();
String script = String.format("window.open('/', '_blank');", url);
((JavascriptExecutor) driver).executeScript(script);
Set newWindowHandles = driver.getWindowHandles();
for(String windowHandle:newWindowHandles)
if(!windowHandles.contains(windowHandle))
selectWindow(windowHandle);
}
To wait for page loading is completed:
public void waitForPageLoaded() {
ExpectedCondition expectation = new ExpectedCondition() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");
}
};
try {
Thread.sleep(1000);
getInstanceWaitDriver().until(expectation);
} catch (Throwable error) {
Assert.fail("Timeout waiting for Page Load Request to complete.");
}
}
where
/**
* Returns instance for current class
*/
public static WebDriverWait getInstanceWaitDriver() {
if (waitDriver == null) {
waitDriver = new WebDriverWait(driver, 30)
}
return waitDriver;
}
}
or just use this
void waitForLoad(WebDriver driver) {
ExpectedCondition pageLoadCondition = new
ExpectedCondition() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
To get the attributes of all the frames on a page:
List frameList = driver.findElements(By.tagName("frame"));
System.out.println("Number of frames in a page :" +frameList.size());
for(WebElement frame : frameList){
//Returns the Id of a frame
System.out.println("Frame Id :" + frame.getAttribute("id"));
//Returns the name of a frame.
System.out.println("Frame fname :" + frame.getAttribute("name"));
}
To switch to the window using a windowId
protected void selectWindow(String windowId) {
for (String handle : driver.getWindowHandles()) {
if (handle.equals(windowId)) {
driver.switchTo().window(handle);
break;
}
}
try {
driver.getWindowHandle();
} catch (NoSuchWindowException ex) {
driver.switchTo().window(driver.getWindowHandles().iterator().next());
}
}
To open the url in new tab
/**
* Opens a new tab for the given URL
* @param url The URL to
* @throws JavaScriptException If unable to open tab
*/
public void openTab(String url) {
String script = "var d=document,a=d.createElement('a');a.target='_blank';a.href='%s';a.innerHTML='.';d.body.appendChild(a);return a";
Object element = ((JavascriptExecutor) driver).executeScript(String.format(script, url));
if (element instanceof WebElement) {
WebElement anchor = (WebElement) element;
anchor.click();
((JavascriptExecutor) driver).executeScript("var a=arguments[0];a.parentNode.removeChild(a);",anchor);
} else {
throw new JavaScriptException(element, "Unable to open tab", 1);
}
}
To switch to the another window
protected void selectOtherWindow() {
String current = driver.getWindowHandle();
int timer = 0;
while (timer < 30) {
if (driver.getWindowHandles().size() > 1)
break;
else {
Thread.sleep(1000);
timer++;
}
}
for (String handle : driver.getWindowHandles()) {
try {
if (handle != current)
driver.switchTo().window(handle);
} catch (Exception e) {
Assert.fail("Unable to select window");
}
}
}
To switch to the another window and close the current window
protected void selectWindowAndCloseCurrent() {
String current = driver.getWindowHandle();
driver.close();
int timer = 0;
while (timer < 30) {
if (driver.getWindowHandles().size() > 1)
break;
else {
Thread.sleep(3000);
timer++;
}
}
for (String handle : driver.getWindowHandles()) {
try {
if (handle != current)
driver.switchTo().window(handle);
} catch (Exception e) {
Assert.fail("Unable to select window");
}
}
}
To get the name of the browser:
The properties appName and appCodeName return the name of the browser
JavascriptExecutor js = (JavascriptExecutor) driver;
System.out.println(js.executeScript("return navigator.appCodeName"));
Be careful: IE11, Chrome, Firefox, and Safari return appName "Netscape".
Chrome, Firefox, IE, Safari, and Opera all return appCodeName "Mozilla".
To get the version of the browser
System.out.println(js.executeScript("return navigator.appVersion"));
Be careful: The information from the navigator object can often be misleading, and should not be used to detect browser versions because:
Different browsers can use the same name
The navigator data can be changed by the browser owner
Some browsers misidentify themselves to bypass site tests
Browsers cannot report new operating systems, released later than the browser
To get the Browser Platform:
The property platform returns the browser platform (operating system)
System.out.println(js.executeScript("return navigator.platform"));
To get the Browser Language
The property language returns the browser's language
System.out.println(js.executeScript("return navigator.language"));
To get the If Java Enabled
The method javaEnabled() returns true if Java is enabled
System.out.println(js.executeScript("return navigator.javaEnabled()"));
To get the color of webelement
String color = driver.findElement(By.id(locator)).getCssValue("color");
You will get “rgba(0, 0, 0, 1)”
To click on the hidden element
/**
* Click hidden element
* @param className - class of the element which will be clicked
* @param numberElement - number of the element which will be clicked
*/
protected void clickInvisibleElementByJs(String className, int numberElement) {
((JavascriptExecutor) driver).executeScript("document.getElementsByClassName('" + className + "')[" + numberElement + "].click();");
}
To scroll your web page:
WebDriver driver = new FirefoxDriver();
((JavascriptExecutor)driver).executeScript("window.scrollBy(0,250)", "");
public void scrollOnBottom() {
((JavascriptExecutor)driver).executeScript("window.scrollTo(0, Math.max($(document).height(), $(window).height()) )");
}
public void scrollToElementBy(By by) {
int yPositionOfElement = driver.findElement(by).getLocation().y;
((JavascriptExecutor)driver).executeScript(String.format("window.scrollTo(0, $s);", yPositionOfElement));
}
To highlight an element
public void highlightTheElement(By by) {
WebElement element = driver.findElement(by);
((JavascriptExecutor) driver).executeScript("arguments[0].style.border='2px solid yellow'", element);
}
To get and set the size of window
public void windowSetSize(Dimension windowSize) {
WebDriver.Window window = driver.getDriver().manage().window();
Dimension size = window.getSize();
System.out.println("Current windowSize = " + size);
window.setSize(windowSize);
System.out.println("New windowSize = " + size);
}
To mouse hover on an element
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();
To interact with textarea elements like a field to adding tags:
WebElement textArea = driver.findElement(By.cssSelector("textarea[placeholder*='Tags']"));
//to focus on the field
new Actions(driver).click(textArea);
//to type value of the tag
textArea.sendKeys("admin");
//to complete adding tag http://joxi.ru/EA4N3aQFzW35mb
textArea.sendKeys(Keys.RETURN);
Dragg & Dropp:
driver.get("http://jqueryui.com/resources/demos/droppable/default.html");
WebElement draggable = driver.findElement(By.id("draggable"));
WebElement droppable = driver.findElement(By.id ("droppable"));
Actions action = new Actions(driver);
action.dragAndDrop(draggable, droppable).perform();
or
new Actions(driver).clickAndHold(draggable).moveToElement(droppable ).release().perform();
Drag an element to an offset
driver.get("http://jqueryui.com/demos/draggable/");
WebElement dragItem = driver.findElement(By.id("draggable"));
(new Actions(driver)).dragAndDropBy(dragItem, 5, 10).build().perform();
Slide:
driver.get("http://jqueryui.com/resources/demos/slider/default.html");
WebElement slider = driver.findElement(By.id("slider"));
Actions action = new Actions(driver);
action.dragAndDropBy(slider, 90, 0).perform();
Re-size:
driver.get("http://jqueryui.com/resources/demos/resizable/default.html");
WebElement resize = driver.findElement(By.xpath("//*[@id='resizable']/div[3]"));
new Actions(driver).dragAndDropBy(resize, 100, 50).perform();
To simulate hovering on Object (for instance, flash video player):
Actions builder = new Actions(driver);
builder.moveToElement(driver.findElement(By.tagName("object")), 100, 100).build().perform();
----***************
Selenium waiting for page to load in Ajax rich applications
By Glib Briia • on June 6, 2016
If it has happened that you are testing web application with lots of Ajax calls that makes parts or the whole pages to reload frequently you might find the code snippets below extremely useful.
In Ajax rich applications, when most of the pages refreshes through the means of Ajax calls, sometimes (in most cases) standard Selenium waitings work unstable or don’t work at all, so the use of custom waitings is often inevitable.
The below code snippet might be useful in those cases:
public static void waitForJQueryProcessing(final WebDriver webDriver, int timeOutInSeconds) {
new WebDriverWait(webDriver, timeOutInSeconds) {
}.until(new ExpectedCondition() {
@Override
public Boolean apply(WebDriver driver) {
return (Boolean) ((JavascriptExecutor) driver)
.executeScript("return window.jQuery != undefined && jQuery.active == 0");
}
});
}
Just using JavascriptExecutor and waiting for jQuery to become inactive can do the trick..
Also, in some cases it might be handy to explicitly wait for DOM to load and become interactive before performing any action:
public static void waitForPageLoad(final WebDriver webDriver, int timeOutInSeconds) {
new WebDriverWait(webDriver, timeOutInSeconds).until(new ExpectedCondition() {
@Override
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete")
|| ((JavascriptExecutor) driver).executeScript("return document.readyState")
.equals("interactive");
}
});
}
Some more info about document.readyState could be found here http://www.w3schools.com/jsref/prop_doc_readystate.asp
Examples above are just the sample ones, there are numerous ways to customize them and possibly get even better results.
seleniumwebdriverwait
--***********************************************
Q) Read Last Line of excel file using selenium?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
public void readExcelFile(String xlsFile) throws IOException{
try{
File f= new File(xlsFile);
if (f.exists()){
System.out.println("***************** File Exits ***********************");
FileInputStream fis= new FileInputStream(f);
@SuppressWarnings("resource")
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row = sheet.getRow(0);
int numCols = row.getLastCellNum();
int totalRows = getExcelLastRow(sheet);
System.out.println( "Num of Rows: "+totalRows +" Num of Cols: "+numCols );
HSSFRow rows = sheet.getRow(totalRows);
for (int i = 0; i<= numCols; i++){
System.out.println(sheet.getRow(totalRows-1).getCell(i).getStringCellValue() );
}
}else{
System.out.println("File Not Found... Please check file...");
}
}catch (Exception e){
System.out.println("Error: "+ e.getMessage());
}
}
public int getExcelLastRow(HSSFSheet sheet){
int lastRow = sheet.getLastRowNum()+1;
return lastRow;
}
--***********************************************
--***********************************************
--***********************************************
--***********************************************
