Showing posts with label selenium. Show all posts
Showing posts with label selenium. Show all posts

Headless execution of test cases using selenium on Firefox with java

package com.sample;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxBinary;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import java.util.concurrent.TimeUnit;
public class HeadlessFirefoxSeleniumSample {
public static void main(String [] args) {
FirefoxBinary firefoxBinary = new FirefoxBinary();
firefoxBinary.addCommandLineOptions("--headless");
FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setBinary(firefoxBinary);
FirefoxDriver driver = new FirefoxDriver(firefoxOptions);
driver.get("http://virtualbuffer.blogspot.com/");
driver.findelement(By.linkText("Log4Net implementation in Visual Studio")).click();
driver.quit();
}
}

Handle windows with Selenium:

 There are test cases in which we need to switch between multiple windows, to automate these test cases using selenium we need to use below functions:
1.getWindowHandle(): This function return parent window reference.
2.getWindowHandles() : This function return all windows reference.
3.switchTo().window(Window) : This function used to switch between windows.
Example:
String Parent_Window = driver.getWindowHandle();
for (String Child_Window : driver.getWindowHandles())
{
driver.switchTo().window(Child_Window);
driver.findElement(By.id("appointment")).click();
driver.findElement(By.id("closeAppointment")).click();
driver.close();
}

driver.switchTo().window(Parent_Window);

Handling Frames in Selenium:

Selenium has multiple methods to handle Frames.
  1. driver.switchTo().frame(name) 
  2. driver.switchTo().frame(id) 
  3. driver.switchTo().frame(index) 
  4. driver.switchTo().frame(iframe_element) 
Example:
<iframe name=”content” id=”contentSection”></iframe>
Multiple options:

driver.switchTo.frame(“content”);
driver.switchTo.frame(“contentSection”);
driver.switchTo.frame(0);
driver.switchTo.frame(driver.findElement(By.cssSelector("iframe[id='contentSection']")
)


To get out of Frame:
driver.SwitchTo().DefaultContent()
Switch to Parent Frame:
driver.switchTo().parentFrame();



Handling keyboard events and mouse actions:

Action class is used to handle keyboard events and mouse actions. Further this class is also used to chain actions or perform multiple actions.

Action name Parameters Description
click WebElement This is used to click in the middle of the element passed as parameter. Like action.click(webelement)
click No Parameter This is used to click at the current location. It is used with combination of actions.
Like action.moveToElement(org.openqa.selenium.WebElement, int, int).click() or action.moveByOffset(int, int).click()
doubleClick WebElement This is used to double click in the middle of the element passed as parameter. Like action.doubleClick(webelement)
doubleClick No Parameter This is used to double click at the current location. It is used with combination of actions.
Like action.moveToElement(org.openqa.selenium.WebElement, int, int).doubleClick() or action.moveByOffset(int, int).doubleClick()
moveToElement WebElement This is used to move mouse pointer to the middle of webelement passed as parameter. The element is scrolled into view. Like action.moveToElement(webelement)
moveToElement WebElement, int, int This is used to move the mouse pointer to offsets from the top left corner of element.The element is scrolled into view. Example: action.moveToElement(webelement, int, int)
moveByOffset int, int This is used to move mouse pointer from current position to the provided offsets. Example: action.moveByOffset(int, int)
keyDown java.lang.CharSequence This is used to perform key press. Remember key is not released automatically, Need to call keyUp() or sendKeys() function. Example: action.keyDown(keys.CONTROL)
keyDown WebElement, java.lang.CharSequence This is used to press key at web element. Example: action.keyDown(webelement, keys.CONTROL)
keyUp Java.lang.CharSequence This is used to keup or release key at current location. Example: action.keyUp(keys.CONTROL)
KeyUp WebElement, Java.lang.CharSequence This is used to press up at web element. Example: action.keyUp(webelement, keys.CONTROL)
sendKeys java.lang.CharSequence This is used to send keys on active element. Example: action.sendKeys(Keys.TAB)
clickAndHold WebElement Click on current mouse location without releasing.
contextClick WebElement Right click on web element. Example: action.contextClick(webelement)
dragAndDrop WebElement, WebElement Perform drag and drop from one element to other.
dragAndDropBy WebElement, int, int Perform drag and drop from one element to co-ordinates.
build No Parameter Used to combine multiple actions into single step. Example:
Actions oAction=new Actions(driver);
Actions moreActions = oAction
.moveToElement(element)
.click()
.keyDown(element,Keys.SHIFT)
.sendKeys(element,"selenium");

Action chaining= moreActions.build();
perform No Parameter For execution of Action object, this method is used. Example:
chaining.perform();

Handling drop-down with Selenium

Selenium Select class is used to perform actions on drop-down:
Different functions provided by Select class:


selectByVisibleText()/deselectByVisibleText()
selects or deselects an option by its visible text from drop down
selectByValue()/deselectByValue()
selects or deselects an option by the value displayed for "value" attribute
selectByIndex()/deselectByIndex()
selects or deselects an option by its index
isMultiple()
returns TRUE if the drop-down allows multiple selection at a time and return FALSE if not allowed
deselectAll()
deselects all selected options



Sample Code:
WebElement dropdown = driver.findElement(By.name("dropdown"));
Select select = new Select(dropdown);

// Here we will perform the multiselect operation in the dropdown.
select.selectByVisibleText("John");

How to Drag and Drop by co-ordinates in Webdriver

 


    WebElement draggable3 = driver.findElement(By.id("ABC"));
        new Actions(driver).dragAndDropBy(draggable3, 400, 90).build().perform();

Check whether Javascript pop up displayed with Webdriver

public boolean isAlertPresent()
{
    try    {
        driver.switchTo().alert();
        return true;
    }   // try    catch (NoAlertPresentException Ex)
    {
        return false;
    }   // catch}
 
 
if(isAlertPresent()){
  driver.switchTo().alert().accept();
} 

Select from drop down using Webdriver

Select oSelection = new Select(driver.findElement(By.id("sampleID")));

    oSelection.selectByIndex(index)

    oSelection.selectByIndex(index)

    // Or

    oSelection.selectByVisibleText(text)

    oSelection.selectByVisibleText(text)

    // Or

    oSelection.selectByValue(value)

    oSelection.selectByValue(value)

Drag and Drop action with Webdriver

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS); 
  WebElement fromElement=driver.findElement(By.id("todrag")); 
  WebElement toElement=driver.findElement(By.id("todrop")); 
     
  Actions builder = new Actions(driver);

1.
builder.dragAndDrop(fromElement, toElement).build().perform();

2.
builder.clickAndHold(fromElement).build().perform();
builder.moveToElement(toElement).build().perform();
builder.release(toElement).build().perform();

3.
builder.dragAndDropBy(fromElement, xoffset, yoffset).perform();
Example: builder.dragAndDropBy(fromElement, -20).perform();

4.
  Action dragAndDrop = builder.clickAndHold(fromElement) 
    .moveToElement(dropElement) 
    .release(toElement) 
    .build();
    dragAndDrop.perform();

Start browser with an extension installed using Webdriver?

final String addOnPath = "C:\\Temp\\addon.xpi";
File AOFile = new File( addOnPath );
FirefoxProfile profile = new FirefoxProfile();
profile.addExtension( AOFile );
WebDriver driver = new FirefoxDriver( profile );


How to interact with hidden elements in Webdriver.

1. WebElement element =driver.findElement(By.id("idElement"));
  ((JavascriptExecutor) driver).executeScript("return arguments[0].getText();", element);
 
2. WebElement element =driver.findElement(By.id("idElement"));
   JavascriptExecutor js = (JavascriptExecutor)driver;
  js.executeScript("arguments[0].click();", element); 
 
3  WebElement element =driver.findElement(By.id("idElement"));
  javascriptExecutor jse = (JavascriptExecutor)driver;
  jse.executeScript("document.getElementsByName('body')[0].setAttribute('type', 'text');");
  element .clear();
  element .sendKeys("text");
 
 
 

Handle File uploading using Webdriver.

We can handle this using java script or by send sendKeys()function:
 
 
1. Using sendKeys():
 
 WebElement upload = driver.findElement(By.id("fileUp"));
        upload.sendKeys("c:/darkbulb.jpg");
        driver.findElement(By.id("submit")).click(); 
 
2. Using Javascript:
 
 WebElement upload = driver.findElement(By.id("fileUp"));
((JavascriptExecutor)driver).executeScript("arguments[0].style.visibility = 'visible';
 arguments[0].style.height = '1px'; arguments[0].style.width = '1px';
 arguments[0].style.opacity =
 1", upload );

How to handle Javascript alerts and prompts with WebDriver?

Use Alert API for this:
 
 
 Get a handle to the open alert, prompt:
Alert alert = driver.switchTo().alert();
// Get the text of the alert or prompt
alert.getText(); 
 // And acknowledge the alert or click "OK"
alert.accept();
 
//Reject the alert or click "NO" 
alert.reject();

Insert text to elements like Div, Span, p tags etc.... [Webdriver]

If user want to insert text to elements like Div, Span, p tags etc....
Need to insert  "innerHTML" using javascript+Webdriver


driver.get("http://virtualbuffer.blogspot.in/");
           String jScript = "var myList = document.
getElementsByClassName(\"post-header\");"
                    +"myList[0].innerHTML=\"YourNumber\";";
                JavascriptExecutor executor = (JavascriptExecutor)driver;
                executor.executeScript(jScript);