Pre-requisite
Java
JDK should install on the system. Also the Java path should be
available in Environment variable. To verify this, see the below screen
–
WebDriver + Eclipse
- Selenium-server-standalone-2.29.0.jar contains the Selenium server (required to use Selenium 1.x classes) and the RemoteWebDriver server, which can be executed via java -jar.
- Selenium-java-2.29.0.zip contains the Java language bindings for Selenium 2.0. All of the necessary dependencies are bundled.
- Launched the eclipse (See the Configuration document and configure accordingly).
- Click File -> New -> Java Projects.
- Shows below screen. Enter the project name (ex – TestLink) and click on Finish. Project will create.
- Right click on the project name and Select New->Folder. Create a folder “lib” under the project name.
- Placed the below downloaded jar files under above created “lib” folder.
selenium-java-2.29.0.jar
selenium-java-standalone-2.29.0.jar
- Right click on project name and select Properties. Click on Java Build Path. Click on Libraries tab.
- Click on Add Jars. Add all the jar files from above create “lib” folder. It looks like the below screen –
- Click on Ok button.
Drivers Initialization (See Example1.java)
- WebDriver Instance
// import the WebDriver Package
import org.openqa.selenium.WebDriver;
//Create an instance of WebDriver
WebDriver driver;
WebDriver driver;
- Initialize Firefox WebDriver
// import the FireFox WebDriver Package
import org.openqa.selenium.firefox.FirefoxDriver;
//Create an instance of WebDriver backed by Firefox
driver = new FirefoxDriver();
driver = new FirefoxDriver();
- Initialize Internet Explorer WebDriver
Download InternetExplorerDriver standalone server from http://code.google.com/p/selenium/downloads/list.
The latest version is IEDriverServer_x64_2.29.1. Follow these steps to
setup your tests for running with InternetExploreDriver:
1. Include the InternetExplorerDriver location in your PATH environment variable OR
2.
Put the “IEDriverServer.exe “ under above created “lib” folder. Specify
its location via the webdriver.ie.driver system property (see sample
below)
//Imort the Internet Explore WebDriver Package
import org.openqa.selenium.ie.InternetExplorerDriver;
//Create an instance of WebDriver backed by IE
System.setProperty("webdriver.ie.driver", "IEDriverServer.exe")
driver = new InternetExplorerDriver();
- Initialize Chrome WebDriver
Download chrome driver from http://code.google.com/p/chromedriver/downloads/list. The latest version is chromedriver_win_26.0.1383.0.zip. Follow these steps to setup your tests for running with ChromeDriver:
1. Include the ChromeDriver location in your PATH environment variable OR
2.
Put the “chromedriver.exe “ under above created “lib” folder . Specify
its location via the webdriver.chrome.driver system property (see sample
below)
// Import the Chrome WebDriver
import org.openqa.selenium.chrome.ChromeDriver;
//Create an instance of WebDriver backed by Chrome
System.setProperty("webdriver.chrome.driver", “chromedriver.exe”);
WebDriver driver = new ChromeDriver();
- Initialize Safari WebDriver
Download Safari driver extension from https://docs.google.com/folder/d/0B5KGduKl6s6-c3dlMWVNcTJhLUk/edit?pli=1. The latest version is SafariDriver2.28.0. Follow these steps to setup your tests for running with SafariDriver:
1. Double click on the downloaded extension. Shows below screen -
2. Click on Install button. Safari extension will install successfully.
// Import the Safari WebDriver
import org.openqa.selenium.safari.SafariDriver;
//Create an instance of WebDriver backed by Chrome
WebDriver driver = new SafariDriver();
- Initialize HtmlUnit WebDriver
// Import the HtmlUnit WebDriver
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
//Create an instance of WebDriver backed by HtmlUnit
WebDriver driver = new HtmlUnitDriver ()
Script – Example1.java
|
/* Script for verifying Drivers Initialization */
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class Example1
{
public static WebDriver driver;
public static void instantiateBrowser(BrowserType browserType, String url)
{
driver = getWebDriver(browserType);
driver.get(url);
closeBrowser();
}
public static void closeBrowser()
{
driver.quit();
}
public static WebDriver getWebDriver(BrowserType browserType)
{
switch (browserType)
{
case FIREFOX:
driver=new FirefoxDriver();
return driver;
case IE:
driver = new InternetExplorerDriver();
return driver;
case CHROME:
//System.setProperty("webdriver.chrome.driver", "D:\\Applications\\Selenium\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
CommonMethods.wait(10000);
return driver;
case HTMLUNIT:
driver = new HtmlUnitDriver();
return driver;
default:
throw new RuntimeException("Browser type unsupported");
}
}
public enum BrowserType
{
FIREFOX, IE, CHROME, HTMLUNIT
}
public static void main (String args[])
{
BrowserType brw=BrowserType.CHROME;
instantiateBrowser(brw,"http://google.co.in");
}
}
|
WebDriver Wait
- Implicit Wait sets internally a timeout that will be used for all consecutive WebElement searches. It will try lookup the element again and again for the specified amount of time before throwing an NoSuchElementException if the element could not have been found. The default setting is 0 once set, the implicit wait is set for the life of the webdriver object instance. See the below example code -
public static void turnOnImplicitWait (WebDriver wd,int timeout)
{
wd.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
}
public static void turnOffImplicitWait (WebDriver wd)
{
wd.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
}
- Explicit Wait is a one-timer used by you for a particular search. It is more extendible in the means that you can set it up to wait for any condition you might like. Usually, you can use some of the prebuilt ExpectedConditions to wait for elements to become clickable, visible, invisible, etc., or just write your own condition that suits your needs. See the below example code –
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element =
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//input[@name='tl_login']")));
- FluentWaitdefines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition. Furthermore, the user may configure the wait to ignore specific types of exceptions whilst waiting, such as NoSuchElementExceptions when searching for an element on the page.
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
public static WebElement fluentWait(final By locator){
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
.withTimeout(30, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver driver)
{
return driver.findElement(locator);
}
});
return foo;
};
Text Verification
There
is no text verification methods (like isTextPresent()) available in
webdriver. Use the below customized code to verify the text present on
the page –
public static boolean verifyTextPresent(WebDriver wd,String text)
{
return wd.getPageSource().contains(text);
}
Script Name - Example5.java
----------------------------------------------------------------------------
//Script of verify page text
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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example5
{
static WebDriver driver;
public static void main(String args[])
{
driver=new FirefoxDriver();
driver.manage().window().maximize();
WebDriverWait wdw = new WebDriverWait(driver, 7);
driver.get("http://localhost/testlink/login.php");
WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']")));
if (driver.getPageSource().contains("Login Name"))
{
System.out.println("Text Found");
}
driver.close();
}
}
----------------------------------------------------------------------------
----------------------------------------------------------------------------
//Script of verify page text
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.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Example5
{
static WebDriver driver;
public static void main(String args[])
{
driver=new FirefoxDriver();
driver.manage().window().maximize();
WebDriverWait wdw = new WebDriverWait(driver, 7);
driver.get("http://localhost/testlink/login.php");
WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']")));
if (driver.getPageSource().contains("Login Name"))
{
System.out.println("Text Found");
}
driver.close();
}
}
----------------------------------------------------------------------------
Page Interaction
Methods
designed for interacting with the element in hand, WebElement also
provides two methods allowing you to search for elements within the
current element’s scope:
Method
|
Purpose
|
findElement(By by)
|
Finds the first element located by the provided method (see Locators table).
|
findElements(By by)
|
Finds all elements located by the provided method.
|
WebDriver
offers for interacting with the elements on that page via its
findElement methods. These methods accept an argument of type By, which
defines several static methods implementing different means of element
location:
Locators
Locator
|
Example (Java)
|
id attribute
|
By.id(“myElementId”)
|
name attribute
|
By.name(“myElementName”)
|
XPATH
|
By.xpath(“//input[@id=’myElementId’]”)
|
Class name
|
By.className(“even-table-row”)
|
CSS Selector
|
By.cssSelector(“h1[title]”)
|
Link Text
|
By.linkText(“Click Me!”)
By.partialLinkText(“ck M”) |
Tag Name
|
By.tagName(“td”)
|
WebElement Methods
Method
|
Purpose
|
clear()
|
Clears all of the contents if the element is a text entity.
|
click()
|
Simulates a mouse click on the element.
|
getAttribute(String name)
|
Returns the value associated with the provided attribute name (if present) or null (if not present).
|
getTagName()
|
Returns the tag name for this element.
|
getText()
|
Returns the visible text contained within this element (including subelements) if not hidden via CSS.
|
getValue()
|
Gets the value of the element’s “value” attribute.
|
isEnabled()
|
Returns true for input elements that are currently enabled; otherwise false.
|
isSelected()
|
Returns true if the element (radio buttons, options within a select, and checkboxes) is currently selected; otherwise false.
|
sendKeys(CharSequence…
keysToSend) |
Simulates typing into an element.
|
setSelected()
|
Select an element (radio buttons, options within a select, and checkboxes).
|
submit()
|
Submits the same block if the element if the element is a form (or contained within a form). Blocks until new page is loaded.
|
toggle()
|
Toggles the state of a checkbox element.
|
WebDriver
provides a support class named Select to greatly simplify interaction
with select elements and their association options:
Method
|
Purpose
|
selectByIndex(int index)/
deselectByIndex(int index) |
Selects/deselects the option at the given index.
|
selectByValue(String value)/
deselectByValue(String value) |
Selects/deselects the option(s) that has a value matching the argument.
|
selectByVisibleText(String text)/
deselectByVisibleTest(String text) |
Selects/deselects the option(s) that displays text matching the argument.
|
deselectAll()
|
Deselects all options.
|
getAllSelectedOptions()
|
Returns a List<WebElement> of all selected options.
|
getFirstSelectedOption()
|
Returns a WebElement representing the first selected option.
|
getOptions()
|
Returns a List<WebElement> of all options.
|
isMultiple()
|
Returns true if this is a multi-select list; false otherwise.
|
You can simulate mouse-hover events and perform drag-and-drop operations using RenderedWebElement.
RenderedWebElement Methods
Method
|
Purpose
|
dragAndDropBy(int moveRightBy,
int moveDownBy) |
Drags
and drops the element moveRightBy pixels to the right and moveDownBy
pixels down. Pass negative arguments to move left and up.
|
dragAndDropOn(RenderedWeb
Element element) |
Drags and drops the element on the supplied element.
|
getLocation()
|
Returns a java.awt.Point representing the top left-hand corner of the element.
|
getSize()
|
Returns a java.awt.Dimension representing the width and height of the element.
|
getValueOfCssProperty(String
propertyName) |
Returns the value of the provided property.
|
hover()
|
Simulates a mouse hover event over the element.
|
isDisplayed()
|
Returns true if the element is currently displayed; otherwise false.
|
Input Text Field
HTML –
<p class="label">Login Name<br />
<input type="text" name="tl_login" id="login" size="32" maxlength="30" />
</p>
<p class="label">Password<br />
<input type="password" name="tl_password" size="32" maxlength="32" />
</p>
|
API –
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@id='login']"));
tlElement=driver.findElement(By.cssSelector("#login"));
tlElement=driver.findElement(By.name("tl_login"));
tlElement=driver.findElement(By.id("login"));
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.sendKeys("admin");
String lname=tlElement.getTagName();
String lname=tlElement.getAttribute("value");
tlElement.clear();
|
Example – Example6.java
//Script of verify input text field
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.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Example6 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); WebDriverWait wdw = new WebDriverWait(driver, 7); driver.get("http://localhost/testlink/login.php"); WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']"))); element.sendKeys("admin"); System.out.println(element.getAttribute("value")); element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_password']"))); element.sendKeys("admin"); System.out.println(element.getAttribute("value")); driver.close(); } } |
Buttons
HTML –
<input type="submit" name="login_submit" value="Login" />
|
API –
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@name='login_submit']"));
tlElement=driver.findElement(By.cssSelector("input[name="login_submit"]"));
tlElement=driver.findElement(By.name("login_submit"));
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.click();
String lname=tlElement.getTagName();
String lname=tlElement.getAttribute("value");
|
Example – Example7.java
//Script of verify buttons
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.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Example7 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); WebDriverWait wdw = new WebDriverWait(driver, 7); driver.get("http://localhost/testlink/login.php"); WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']"))); element.sendKeys("admin"); System.out.println(element.getAttribute("value")); element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_password']"))); element.sendKeys("admin"); System.out.println(element.getAttribute("value")); element=driver.findElement(By.xpath("//input[@name='login_submit']")); element.click(); driver.switchTo().defaultContent(); driver.switchTo().frame("titlebar"); driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click(); driver.close(); } } |
Links
HTML –
<p>
<a href="firstLogin.php">New User?</a><br />
<a href="lostPassword.php">Lost Password?</a>
</p>
<p>
TestLink project <a href="http://testlink.sourceforge.net/docs/testLink.php">Home</a><br />
TestLink is licensed under the <a href="http://www.gnu.org/copyleft/gpl.html">GNU GPL</a>
</p>
|
API –
List<WebElement> MyList = driver.findElements(By.tagName("a"));
MyList .get(i).getText() – Get text of links
MyList.get(i).getAttribute("href") – Get links
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("////a[contains(text(),'Home')]"));
tlElement=driver.findElement(By.linkText("Home"));
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.click();
String lname=tlElement.getTagName();
|
Example - Example8.java
//Script of verify links
import java.util.List; 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.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; public class Example8 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); WebDriverWait wdw = new WebDriverWait(driver, 7); driver.get("http://localhost/testlink/login.php"); WebElement element = wdw.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[@name='tl_login']"))); List<WebElement> all_links=driver.findElements(By.tagName("a")); int count=all_links.size(); for(int i=0;i<count;i++) { String linkname=all_links.get(i).getAttribute("href"); System.out.println(linkname); } driver.close(); } } |
Moving Between Frames
HTML –
<frame src="lib/general/navBar.php" name="titlebar" scrolling="no" noresize="noresize" />
<frame src="lib/general/mainPage.php" scrolling='auto' name='mainframe' />
|
API –
driver.switchTo().frame("mainframe");
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
|
Example - Example9.java
//Script of verify Selection box
import java.util.List; 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 Example9 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("http://localhost/testlink/login.php"); WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']")); element.sendKeys("admin"); element = driver.findElement(By.xpath("//input[@name='tl_password']")); element.sendKeys("admin"); element=driver.findElement(By.xpath("//input[@name='login_submit']")); element.click(); driver.switchTo().frame("mainframe"); List<WebElement> options = driver.findElements(By.tagName("option")); System.out.println(options.size()); for (WebElement option : options) { System.out.println(option.getText()); } System.out.println("----------------------------------------"); Select select=new Select(driver.findElement(By.xpath("//select[@name='docs']"))); options=select.getOptions(); for (WebElement option : options) { System.out.println(option.getText()); } select.selectByIndex(1); //driver.switchTo().defaultContent(); //driver.switchTo().frame("titlebar"); //driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click(); //driver.close(); } } |
Selection Box
HTML –
<select class="menu_combo" style="font-weight:normal;" name="docs" size="1"
onchange="javascript:get_docs,'http://localhost/testlink/');" >
<option value="leer"> -Choose Document-</option>
<option value="Configuration_of_FCKEditor_and_CKFinder.pdf">Configuration_of_FCKEditor_and_CKFinder.pdf</option>
<option value="customfields_for_computing_times.txt">customfields_for_computing_times.txt</option>
<option value="excel2TestLink.pdf">excel2TestLink.pdf</option>
<option value="glosary.html">glosary.html</option>
<option value="remote_execution_quick_start.txt">remote_execution_quick_start.txt</option>
<option value="samples.txt">samples.txt</option>
<option value="testlink_installation_manual.pdf">testlink_installation_manual.pdf</option>
<option value="testlink_user_manual.pdf">testlink_user_manual.pdf</option>
<option value="tl-bts-howto.pdf">tl-bts-howto.pdf</option>
<option value="tl-file-formats.pdf">tl-file-formats.pdf</option>
<option value="youtrack-readme.pdf">youtrack-readme.pdf</option>
</select>
|
API –
List<WebElement> options = driver.findElements(By.tagName("option"));
System.out.println(options.size());
for (WebElement option : options)
{
System.out.println(option.getText());
}
or
Select select=new Select(driver.findElement(By.xpath("//select[@name='docs']")));
options=select.getOptions();
for (WebElement option : options)
{
System.out.println(option.getText());
}
select.selectByVisibleText("-Choose Document-");
select.selectByIndex(1);
|
Example - See the above Example9.java script
|
Radio Button and Checkboxes
HTML –
<td>
<input type="checkbox" name="active" checked="checked" />Active</td>
</tr>
<tr>
<td></td><td>
<input type="checkbox" name="is_public" checked="checked"/>Public</td>
</tr>
|
API –
public static WebElement tlElement;
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement=driver.findElement(By.cssSelector("input[name=\"active\"]"));
tlElement=driver.findElement(By.name("active"));
tlElement.isDisplayed()
tlElement.isEnabled()
tlElement.isSelected()
tlElement.click();
|
Example - Example10.java
//Radio Buttons and Check Boxes
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; public class Example10 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("http://localhost/testlink/login.php"); WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']")); element.sendKeys("admin"); element = driver.findElement(By.xpath("//input[@name='tl_password']")); element.sendKeys("admin"); element=driver.findElement(By.xpath("//input[@name='login_submit']")); element.click(); driver.switchTo().frame("mainframe"); driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click(); driver.findElement(By.xpath("//input[@name='create']")).click(); element=driver.findElement(By.xpath("//input[@name='active']")); if (element.isDisplayed()) { System.out.println("checkbox found"); } if (element.isEnabled()) { System.out.println("checkbox is enabled"); } if (element.isSelected()) { System.out.println("Checkbox is selected"); } element.click(); driver.switchTo().defaultContent(); driver.switchTo().frame("titlebar"); driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click(); driver.close(); } } |
Handle Text Editable area –
HTML –
<tr>
<td>Project description</td>
<td
style="width:80%"><input type="hidden" id="notes"
name="notes" value="" style="display:none" /><input
type="hidden" id="notes___Config"
value="CustomConfigurationsPath=http://localhost/testlink/cfg/tl_fckeditor_config.js"
style="display:none" /><iframe id="notes___Frame"
src="http://localhost/testlink/third_party/fckeditor/editor/fckeditor.html?InstanceName=notes&Toolbar=tl_default"
width="100%" height="200" frameborder="0"
scrolling="no"></iframe></td>
</tr>
|
API –
driver.switchTo().frame("notes___Frame");
WebElement editable = driver.switchTo().activeElement();
editable.sendKeys("Project for Selenium with Java with TestNG");
|
Example - Example11.java script
//Verify Text Area
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; public class Example11 { static WebDriver driver; public static void main(String args[]) { driver=new FirefoxDriver(); driver.manage().window().maximize(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("http://localhost/testlink/login.php"); WebElement element = driver.findElement(By.xpath("//input[@name='tl_login']")); element.sendKeys("admin"); element = driver.findElement(By.xpath("//input[@name='tl_password']")); element.sendKeys("admin"); element=driver.findElement(By.xpath("//input[@name='login_submit']")); element.click(); driver.switchTo().frame("mainframe"); driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click(); driver.findElement(By.xpath("//input[@name='create']")).click(); driver.switchTo().frame("notes___Frame"); WebElement editable = driver.switchTo().activeElement(); editable.sendKeys("TestLink Project for Selenium with Java"); driver.switchTo().defaultContent(); driver.switchTo().frame("titlebar"); driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click(); driver.close(); } } |
Pop Up handle
API –
String parentWindowHandle = driver.getWindowHandle();
WebDriver popup = driver.switchTo().window("FileUpload");
popup.findElement(By.xpath("//input[@id='title']")).sendKeys("test");
popup.findElement(By.xpath("//input[@value='Cancel']")).click();
driver.switchTo().window(parentWindowHandle);
|
//Example - Example12.java script
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; public class Example12 { public static WebDriver driver; public static WebElement tlElement; public static void main (String args[]) { driver=new FirefoxDriver(); driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS); driver.get("http://localhost/testlink/index.php"); driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin"); driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin"); driver.findElement(By.xpath("//input[@name='login_submit']")).click(); driver.switchTo().frame("mainframe"); driver.findElement(By.xpath("//a[contains(text(),'Test Specification')]")).click(); driver.switchTo().frame("treeframe"); driver.findElement(By.cssSelector("#extdd-3")).click(); driver.switchTo().defaultContent(); driver.switchTo().frame("mainframe"); driver.switchTo().frame("workframe"); driver.findElement(By.xpath("//input[@value='Upload new file']")).click(); String parentWindowHandle = driver.getWindowHandle(); System.out.println(parentWindowHandle); WebDriver popup = driver.switchTo().window("FileUpload"); popup.findElement(By.xpath("//input[@id='title']")).sendKeys("test"); popup.findElement(By.cssSelector("input[name=\"uploadedFile\"]")).sendKeys("C:\\file.jpg");//click(); popup.findElement(By.xpath("//input[@value='Cancel']")).click(); driver.switchTo().window(parentWindowHandle); driver.switchTo().defaultContent(); driver.switchTo().frame("titlebar"); driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click(); driver.quit(); } } |
Mouse hover example
API –
public static WebDriver driver;
public static WebElement mnuElement,subElement;
Actions builder = new Actions(driver);
builder.moveToElement(mnuElement).perform();//Move the mouse on main menu to display the sub menu
Thread.sleep(2000);
builder.moveToElement(subElement);
builder.click().perform();//Click on the sub menu
|
//Example – Example13.java script
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.interactions.Actions; import org.openqa.selenium.support.ui.FluentWait; import org.openqa.selenium.support.ui.Wait; import com.google.common.base.Function; public class Example13 { public static WebDriver driver; public static WebElement fluentWait(final By locator){ Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) .withTimeout(50, TimeUnit.SECONDS) .pollingEvery(5, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class); WebElement foo = wait.until(new Function<WebDriver, WebElement>() { public WebElement apply(WebDriver driver) { return driver.findElement(locator); } } ); return foo; }; public static void main (String args[]) throws InterruptedException { driver=new FirefoxDriver(); driver.get("http://shopping.indiatimes.com"); WebElement element=fluentWait(By.xpath("//div/descendant::div[@id='shopbybrand']")); if (element.getText().equals("Shop by Brand")) { System.out.println("Element Found"); } element = driver.findElement(By.xpath("(//a[contains(text(),'More')])[2]")); Actions builder = new Actions(driver); builder.moveToElement(element).perform(); element=fluentWait(By.xpath("//a[contains(text(),'Nokia Shop')]")); builder.moveToElement(element); builder.click().perform(); driver.quit(); } } |
SELENIUM RC EMULATION
It
is possible to emulate Selenium Remote Control (RC) using the WebDriver
Java implementation on any of its supported browsers. This allows you
to maintain both WebDriver and Selenium test assets side by side and to
engage in an incremental migration from Selenium to WebDriver. In
addition, running the normal Selenium RC server is not required.
WebDriver driver = new FirefoxDriver();String baseUrl = "http://www.google.com";
// Create the Selenium implementation
Selenium selenium = new WebDriverBackedSelenium(driver, baseUrl);
// Perform actions with selenium
selenium.open("http://www.google.com");
selenium.type("name=q", "cheese");
selenium.click("name=btnG");
// Get the underlying WebDriver implementation back.
WebDriver driverInstance = ((WebDriverBackedSelenium) selenium).getWrappedDriver();
//Finally, close the browser.
selenium.stop();
Configure WebDriver using JUnit and Ant
This post contains the information for configure the Eclipse with Selenium Webdriver, JUnit and Ant.
Pre-Requisite –
Java JDK should be installed on system. To verify and set the JAVA_HOME, follow the below steps –
For verification of Java installation on System -
C:\Users>java -version
java version "1.7.0_06"
Java(TM) SE Runtime Environment (build 1.7.0_06-b24)
Java HotSpot(TM) Client VM (build 23.2-b09, mixed mode, sharing)
Configure Eclipse -
- Download Eclipse (eclipse-SDK-4.2-win32.zip) from the site www.eclipse.org.
- Extract the zip file and put the eclipse folder in any directory (In my case – D:\eclpse for Windows).
- Launch the eclipse.exe file. Shows below screen.
- Enter the workspace location and Click on Ok button.
- Eclipse editor will launch. Close the Welcome screen. Shows below screen.
Configure JUnit in Eclipse –
Advantages:
- Very good reporting structure is available
- Can generate XML, HTML reports
- There are options available to create test methods, test suites, etc
- Utilize Selenium IDE or Firebug / Firepath to record test scripts
Disadvantages:
- We will not be able to define our own reporting format
Steps to Execute JUnit Scripts
- Install Eclipse (See the section Configure Eclipse) and launch it.
- Download the JUnit jar file from the site - https://github.com/KentBeck/junit/downloads. The latest JUnit jar file is unit-4.10.jar
- In Eclipse, Click File > New > Java Projects.
- Shows below screen. Enter the project name (ex – TestLink) and click on Finish.
- New project will create and shows in Eclipse editor.
- Right click on the project name and Select New->Folder. Create a folder “lib” under the project name.
- Download the below jar files and placed under above created “lib” folder.
selenium-java-2.29.0.jar
selenium-java-standalone-2.29.0.jar
junit-4.10.jar
- Right click on project name and select Properties. Click on Java Build Path.
- Click on Libraries tab.
- Click on Add External Jars. Add all the Jar files (Selenium and junit) from above create “lib” folder. It looks like the below screen –
- Click on Ok button.
- Execute the scripts JUnitExample.java and JUnitExample1.java. For executing this, right click on this script, and select Run As-> JUnit Test.
Scripts Details –
- JUnitExample_SingleTest.java – This JUnit script contains only one test so we have the annotation @Before, @After and @Test.
Script Name - JUnitExample_SingleTest.java
|
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class JUnitExample_SingleTest
{
WebDriver driver;
public static WebElement tlElement;
@Before
public void setUp() throws Exception
{
driver= new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("http://localhost/testlink/login.php");
driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='login_submit']")).click();
}
@Test
public void testProject() throws InterruptedException
{
driver.switchTo().frame("mainframe");
driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
driver.findElement(By.xpath("//input[@name='create']")).click();
Thread.sleep(20);
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement.click();
}
@After
public void tearDown() throws Exception
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
}
}
|
- JUnitExample_MultiTests.java - This JUnit script contains more than one tests so we have the annotations @BeforeClass, @AfterClass and @Test. In that case, SetUp and teardown methods will execute only one time i.e before test execution and after test execution completes.
Script Name - JUnitExample_MultiTests.java
|
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
public class JUnitExample_MultiTests
{
public static WebDriver driver;
public static WebElement tlElement;
@BeforeClass
public static void setUp() throws Exception
{
driver= new FirefoxDriver();
driver.get("http://localhost/testlink/login.php");
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
}
@Test
public void test1() {
System.out.println("@Test test1()");
driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='login_submit']")).click();
}
@Test
public void test2() {
System.out.println("@Test test2()");
driver.switchTo().frame("mainframe");
driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
driver.findElement(By.xpath("//input[@name='create']")).click();
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement.click();
}
@AfterClass
public static void tearDown() throws Exception
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
}
}
|
-
Configure Eclipse + WebDriver + JUnit + ANT
For Configuring Ant, see the below steps –
- Download ANT from Apache web site (http://ant.apache.org/bindownload.cgi).
- Unzip the ant and copy to C:\Ant folder (or can choice your any hard disk folder). In my case, I kept under D:\Applications\Ant.
- Configure environment variables: ANT_HOME
Script Execution with Ant –
- Will use the same above created Junit script.
- First, need to create build.xml file. See the below xml file corresponding to JUnitExample_SingleTest.java and JUnitExample_MultiTests.java scripts.
<?xml version="1.0" encoding="UTF-8"?>
<project name="TestLink" default="exec" basedir=".">
<property name="src" value="./src" /><!-- Change it to your source folder -->
<property name="lib" value="./lib" /><!-- Change it to your lib folder -->
<property name="bin" value="./bin" /><!-- Change it to your bin folder -->
<property name="report" value="./report" /><!-- Change it to your report folder -->
<path id="test.classpath"><!-- Creating a classpath for use while compiling -->
<pathelement location="${bin}" />
<fileset dir="${lib}">
<include name="**/*.jar" />
</fileset>
</path>
<target name="init"><!-- Initialization target which deletes and recreates the binary folder.-->
<delete dir="${bin}" />
<mkdir dir="${bin}" />
</target>
<!--Section1-->
<target name="compile" depends="init"><!-- Target for compiling the source folder -->
<javac source="1.7" srcdir="${src}" fork="true" destdir="${bin}" >
<classpath>
<pathelement path="${bin}">
</pathelement>
<fileset dir="${lib}">
<include name="**/*.jar" />
</fileset>
</classpath>
</javac>
</target>
<target name="exec" depends="compile">
<delete dir="${report}" />
<mkdir dir="${report}" />
<mkdir dir="${report}/xml" />
<junit printsummary="yes" haltonfailure="no">
<classpath>
<pathelement location="${bin}" />
<fileset dir="${lib}">
<include name="**/*.jar" />
</fileset>
</classpath>
<!--Section2-->
<formatter type="plain"/>
<formatter type="xml"/>
<batchtest fork="yes" todir="${report}/xml">
<fileset dir="${src}">
<include name="**/JUnitExample*.java"/>
<exclude name="**/Example*.java"/>
</fileset>
</batchtest>
</junit>
<junitreport
todir="${report}"><!-- This section generated the Junit
report in html to "html" folder from the xml file. -->
<fileset dir="${report}/xml">
<include name="TEST*.xml" />
</fileset>
<report format="frames" todir="${report}/html" />
</junitreport>
</target>
</project>
|
Note
– If you are using any other Java version then go to
<!--Section1--> and set the value of “javac source”. By default,
its set to 1.
- Go to command prompt – > navigate to folder where the build.xml is kept ( In my case, the path is - D:\Automation\Selenium\TestLink\TestLink).
- Execute the following command: ant (press enter). This should fire the Selenium tests and generate the HTML / XML reports and put them into the report folder.
- After the execution, it creates one more folder – > report and it contains HTML reports that should look as below (Go to the “report” directory and double click on the “index.html” to view the complete report):
Configure WebDriver using TestNG and ReportNG
This post contains the information for configure the Eclipse with Selenium Webdriver, TestNG, and ReportNG.
Pre-Requisite –
Java JDK should be installed on system. To verify and set the JAVA_HOME, follow the below steps –
For verification of Java installation on System -
C:\Users>java -version
java version "1.7.0_06"
Java(TM) SE Runtime Environment (build 1.7.0_06-b24)
Java HotSpot(TM) Client VM (build 23.2-b09, mixed mode, sharing)
Configure Eclipse -
- Download Eclipse (eclipse-SDK-4.2-win32.zip) from the site www.eclipse.org.
- Extract the zip file and put the eclipse folder in any directory (In my case – D:\eclpse for Windows).
- Launch the eclipse.exe file. Shows below screen.
- Enter the workspace location and Click on Ok button.
- Eclipse editor will launch. Close the Welcome screen. Shows below screen.
Configure WebDriver + TestNG + ReportNGin Eclipse -
8) After few minutes, TestNG plugin install completes. You need to restart the eclipse for updating the installed plugin.
11) New project will create. Shows below screen.
12) Right click on the project name and Select New->Folder. Create a folder “lib” under the project name.
13) Download the below jar files and placed under above created “lib” folder.
selenium-java-2.29.0.jar
selenium-java-standalone-2.29.0.jar
testng-6.5.2.jar
reportng-1.1.3.jar
guice-3.0.jar
velocity-dep-1.4.jar
16) Click on Add External Jars. Add all the jar files from above create “lib” folder. It looks like the below screen –
17) Click on Ok button.
TestNG Script Execution –
1) Execute the script testNGExample.java
Script Name - testNGExample.java
|
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.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class testNGExample
{
public static WebDriver driver;
public static WebElement tlElement;
@BeforeTest
public void startDriver()
{
driver= new FirefoxDriver();
driver.get("http://localhost/testlink/login.php");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test
public void test1()
{
System.out.println("@Test test1()");
driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin");
driver.findElement(By.xpath("//input[@name='login_submit']")).click();
}
@Test(dependsOnMethods="test1")
public void test2()
{
System.out.println("@Test test2()");
driver.switchTo().frame("mainframe");
driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
driver.findElement(By.xpath("//input[@name='create']")).click();
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement.click();
}
@AfterTest
public void stopDriver()
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
}
}
|
3) TestNG Report (Check the file “emailable-report.html” under test-output folder. You can also check the file “index.html”)-
TestNG+ReportNG script execution
1) Get the “reportNG.xml” file and placed under the above created project folder. It looks like below –
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite verbose="0" name="TestLink Suite">
<listeners>
<listener class-name="org.uncommons.reportng.HTMLReporter"/>
</listeners>
<test verbose="2" name="TestProjectManagement" preserve-order="false">
<classes>
<class name="reportNGExample"/>
</classes>
</test>
</suite>
|
2) Now time to run the script. We have used the “reportNGExample.java” script.
Script Name - reportNGExample.java
|
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.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import org.testng.Reporter;
public class reportNGExample
{
public static WebDriver driver;
public static WebElement tlElement;
@BeforeTest
public void startDriver()
{
driver= new FirefoxDriver();
driver.get("http://localhost/testlink/login.php");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Reporter.log("1.Open Login screen");
}
@Test
public void test1()
{
System.out.println("@Test test1()");
driver.findElement(By.xpath("//input[@name='tl_login']")).sendKeys("admin");
Reporter.log("2.Enter user name");
driver.findElement(By.xpath("//input[@name='tl_password']")).sendKeys("admin");
Reporter.log("3.Enter Password");
driver.findElement(By.xpath("//input[@name='login_submit']")).click();
Reporter.log("4.Login into TestLink");
}
@Test(dependsOnMethods="test1")
public void test2()
{
System.out.println("@Test test2()");
driver.switchTo().frame("mainframe");
driver.findElement(By.xpath("//a[contains(text(),'Test Project Management')]")).click();
Reporter.log("1.Click on Project Management");
driver.findElement(By.xpath("//input[@name='create']")).click();
Reporter.log("2.Click on create button");
tlElement=driver.findElement(By.xpath("//input[@name='active']"));
tlElement.click();
Reporter.log("3.Click on Active checkbox");
}
@AfterTest
public void stopDriver()
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
}
}
|
4) Verify the report. Go to the project Folder/test-output/html. Open the “index.html”. The report looks like the below screen
Simple WebDriver Framework using Java
This post contains the information about setting up simple WebDriver framework. The
framework is created to keep the design as much as simple, easy to
understand and extendible. I have used TestLink webapp to use as an
example (For TestLink configuration, visit the page – http://testlinkconfiguration.blogspot.in/).
Technologies Used –
- Selenium 2.0 (WebDriver) – For UI Automation.
- JUnit – For Unit Test.
- Ant – For Report Generation
Pre-requisites -
Java should be available –
Java JDK (greater than 1.5) should be installed on the system.
Required Jar Files –
selenium-java-2.29.0.jar
selenium-java-standalone-2.29.0.jar
junit-4.10.jar
Required Browser related files –
Chromedriver.exe (http://code.google.com/p/chromedriver/downloads/list)
IEDriverServer.exe (http://code.google.com/p/selenium/downloads/list)
SafariDriver2.28.0.safariextz (https://docs.google.com/folder/d/0B5KGduKl6s6-c3dlMWVNcTJhLUk/edit?pli=1)
Framework Highlights –
- Used basic Java features, JUnit and Ant for creating and executing scripts.
- Methods common across the scripts has defined in the “CommonFuntions.java” file. So all the scripts can use the methods from this file.
- Web page elements, Browsers name and values are contained in properties file called “TestLink.properties” file. Scripts only contain the variable name from this properties file. This reduces the dependency of hardcore values from the scripts.
- Created source folders for every TestLink modules (ex – TestProject, TestSpecifications etc) so we have scripts based on the features and can easily mapped the test cases.
- Every source folder/feature has at least one main file (ex - TestProject_Main.java) which contains all the test cases respectively. Because of this we can also execute the scripts based on the features.
- All the jar files and required browser related files are stored under “lib” folder.
Framework Design -
- Download Eclipse (eclipse-SDK-4.2-win32.zip for Windows or eclipse-SDK-4.2-macosx-cocoa-x86_64.tar) from the site www.eclipse.org
- Extract the zip file and put the eclipse folder in any directory (In my case – D:\eclipse for Windows or /Users/<username>/eclipse on Mac.
- Launch Eclipse. Browse the path of your workspace. Click on ‘OK’ button.
- Select File->New->Java Project from Eclipse main menu.
- Enter the Project name (ex- TestLink_Automation_V0) on below screen. Click on Finish button.
- Now the project name (ex - TestLink_Automation_V0) appears in Eclipse. See below screen –
- Right click on project name (ex - TestLink_Automation_V0) and select New->Folder menu.
- Enter the Folder name “lib” and click on Finish button. See the below screen -
- Now Package Explorer looks like this –
- Copy all the below jar and browsers related files into this “lib” folder –
a. selenium-java-2.29.0.jar
b. selenium-java-standalone-2.29.0.jar
c. selenium-java-2.29.0-srcs.jar
d. junit-4.10.jar
e. chromedriver.exe
f. IEDriverServer.exe
g. SafariDriver2.28.0.safariextz
- Select Project name from Package Explorer. Click on Project->Properties from Eclipse main menu. Shows below screen.
- Select “Java Build Path” from left side. Click on Libraries tab. Shows above screen.
- Click on “Add JARs..” button. Expand the Project name and then lib folder.
- Select all the Jar files and click on Ok button. Shows below screen –
- Click Ok button on Java Build Path screen.
- Right click on project name and select New->Source Folder
- Enter the Source Folder name.
- Click on Finish button. Now Package Explorer looks like below –
- Repeat the steps 16-18 for another source folder (ex – User Management). Note – For any other source folder, follow the same steps.
- Create common function java file. This file contains the methods which have been used across all the scripts. For creating this, right click on the project and select New->Class.
- Enter the Class name and click on Finish button.
- Create Properties file. This file contains all the application controls, hardcore values, setting browser name etc which have been used across the scripts. For creating this, right click on the project and select New->File menu.
- Enter the File name (ex - TestLink.properties) and click on Finish button.
- Start creating test scripts. For creating this, right click on source folder (ex - TestProject) and select New->Class. Enter the Class name and click on finish button.
- Create “build.xml” file for running script using Ant and get the HTML report. For creating this file, right click on the project and select New->File menu. Enter the file name “build.xml” and click on Finish button.
- Now project framework looks like below -
Creating Properties (TestLink.properties) file –
Web
page elements, Browsers name and values are contained in properties
file called “TestLink.properties” file. Scripts only contain the
variable name from this properties file. This
reduces the dependency of hardcore values from the scripts. Normally we
create the property variable and assign into the respective variable.
Ex –
In
the script, you can simply use the variable. Later if there is any
change in value, we only need to update the properties file not all the
script files.
Loading Properties file –
Java
provides the utility to load the properties file and get the individual
property from this. See the below code to load the properties file –
Properties prop = new Properties();
try {
//load a properties file
prop.load(new FileInputStream("TestLink.properties"));
} catch (IOException ex) {
ex.printStackTrace();
}
Details about common functions –
Methods
common across the scripts has defined in the “CommonFuntions.java”
file. So all the scripts can use the methods from this file. See below
the current common methods are –
Details about Test Script design –
We have used JUnit for creating and executing test cases. The test scripts has divided into three sections –
1) setup
2) Test Script
3) Teardown
- SetUp method – This method contains the initialization of variables, properties and browser driver and application URL. See the below code block as an example –
@BeforeClass
public static void setUp() throws IOException
{
try {
//load a properties file
prop.load(new FileInputStream("TestLink.properties"));
} catch (IOException ex)
{
ex.printStackTrace();
}
driver=CommonFunctions.getWebDriver(prop);
driver.manage().deleteAllCookies();
wdw = new WebDriverWait(driver, 30);
driver.get("http://localhost/testlink/login.php");
driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
}
- Test Script – The test script is divided into two parts – First, call the test script from main file and second, actual implementation of test case is in separate file. See the below example code –
@Test
public void test1_VerifyLoginNameHeader()
{
System.out.println("@Test Case-1:Verify LoginName in header on the home page");
TestProject_TCases.TestCase1(driver, wdw, prop);
}
- TearDown – This method contains the application logout, closing the app and browser. See the below code example –
@AfterClass
public static void tearDown()
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
CommonFunctions.wait(100);
}
Script Executing mode – Using this framework, we can execute the script in two modes –
1) Using JUnit
2) Using Ant.
Example Scripts
- Put the Files TestProject_Main.java and TestProject_TCases.java under TestProject source folder.
- Put the TestLink.properties and CommonFunctions.java files directly under “TestLink_Automation_V0” project
TestProject_Main.java
|
import
java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import
java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import
org.openqa.selenium.support.ui.WebDriverWait;
public class TestProject_Main
{
public static WebDriver driver;
public static WebElement element;
public static WebDriverWait wdw;
public static Properties prop = new Properties();
@BeforeClass
public static void setUp() throws IOException
{
try {
//load a properties file
prop.load(new
FileInputStream("TestLink.properties"));
} catch
(IOException ex)
{
ex.printStackTrace();
}
driver=CommonFunctions.getWebDriver(prop);
driver.manage().deleteAllCookies();
wdw = new WebDriverWait(driver,
30);
driver.get("http://localhost/testlink/login.php");
driver.manage().timeouts().implicitlyWait(20,
TimeUnit.SECONDS);
driver.findElement(By.xpath(prop.getProperty("TXT_UNAME"))).sendKeys("admin");
driver.findElement(By.xpath(prop.getProperty("TXT_PWD"))).sendKeys("admin");
driver.findElement(By.xpath(prop.getProperty("BTN_LOGIN"))).click();
CommonFunctions.wait(100);
}
@Test
public void
test1_VerifyTestProjectMangtLink()
{
System.out.println("@Test
Case-1:Verify Test Project Management on the home page");
TestProject_TCases.TestCase1(driver,
wdw, prop);
}
@Test
public void
test2_VerifyAssignUserRolesLink()
{
System.out.println("@Test
Case-2:Verify Assign User Role on the home page");
TestProject_TCases.TestCase2(driver,
wdw, prop);
}
@AfterClass
public static void tearDown()
{
driver.switchTo().defaultContent();
driver.switchTo().frame("titlebar");
driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
driver.quit();
CommonFunctions.wait(100);
}
}
|
TestProject_TCases.java
|
import java.util.Properties;
import org.openqa.selenium.By;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.support.ui.WebDriverWait;
public class
TestProject_TCases
{
//Test1
public static void
TestCase1(WebDriver wd,WebDriverWait wd_wait,Properties prop)
{
wd.switchTo().frame("mainframe");
WebElement
element=wd.findElement(By.xpath(prop.getProperty("LNK_TESTPRJMANM")));
if(element.isDisplayed())
{
element.click();
System.out.println("Click
on the Test Project Management link");
}
CommonFunctions.wait(100);
wd.switchTo().defaultContent();
wd.switchTo().frame("titlebar");
wd.findElement(By.xpath(prop.getProperty("TAB_PROJECT"))).click();
}
//Test2
public static void
TestCase2(WebDriver wd,WebDriverWait wd_wait,Properties prop)
{
wd.switchTo().frame("mainframe");
WebElement
element=wd.findElement(By.xpath(prop.getProperty("LNK_USERROLE")));
if(element.isDisplayed())
{
element.click();
System.out.println("Click
on the Assign User Roles link");
}
CommonFunctions.wait(100);
wd.switchTo().defaultContent();
wd.switchTo().frame("titlebar");
wd.findElement(By.xpath(prop.getProperty("TAB_PROJECT"))).click();
}
}
|
TestLink.properties
|
#Please use the following
browsers - FIREFOX, IE, CHROME, HTMLUNIT, ANDROID, SAFARI
BROWSER=FIREFOX
#TestLink Login
TXT_UNAME=//input[@name='tl_login']
TXT_PWD=//input[@name='tl_password']
BTN_LOGIN=//input[@name='login_submit']
#Home Screen - Tabs
TAB_PROJECT=//a[contains(text(),'Project')]
#Home Screen - Test Project
LNK_TESTPRJMANM=//a[contains(text(),'Test
Project Management')]
LNK_USERROLE=//a[contains(text(),'Assign User Roles')]
|
CommonFunctions.java
|
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import
java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import
org.openqa.selenium.NoSuchElementException;
import
org.openqa.selenium.WebDriver;
import
org.openqa.selenium.WebElement;
import
org.openqa.selenium.android.AndroidDriver;
import
org.openqa.selenium.chrome.ChromeDriver;
import
org.openqa.selenium.firefox.FirefoxDriver;
import
org.openqa.selenium.htmlunit.HtmlUnitDriver;
import
org.openqa.selenium.ie.InternetExplorerDriver;
import
org.openqa.selenium.safari.SafariDriver;
import
org.openqa.selenium.support.ui.FluentWait;
import
org.openqa.selenium.support.ui.Wait;
import
com.google.common.base.Function;
public class CommonFunctions
{
public static void wait(int n)
{
long t0,t1;
t0=System.currentTimeMillis();
do{
t1=System.currentTimeMillis();
}
while(t1-t0<n);
}
public static WebDriver getWebDriver(Properties
prop) throws IOException
{
WebDriver wd;
File directory = new File
(".");
String
browser_name=prop.getProperty("BROWSER");
switch (BrowserType.valueOf(browser_name))
{
case FIREFOX:
wd=new FirefoxDriver();
wd.manage().window().maximize();
return wd;
case IE:
String
iepath=directory.getCanonicalPath() + "/lib/" +
"IEDriverServer.exe";
//System.out.println(iepath);
System.setProperty("webdriver.ie.driver",iepath);
wd
= new InternetExplorerDriver();
wd.manage().window().maximize();
return wd;
case CHROME:
String
chromepath=directory.getCanonicalPath() + "/lib/" +
"chromedriver.exe";
//System.out.println(driverpath);
System.setProperty("webdriver.chrome.driver",
chromepath);
wd
= new ChromeDriver();
CommonFunctions.wait(5000);
wd.manage().window().maximize();
return wd;
case HTMLUNIT:
wd
= new HtmlUnitDriver();
return wd;
case ANDROID:
wd
= new AndroidDriver();
return wd;
case SAFARI:
wd
= new SafariDriver();
wd.manage().window().maximize();
return wd;
default:
throw new
RuntimeException("Browser type unsupported");
}
}
public static enum BrowserType
{
FIREFOX, IE, CHROME, HTMLUNIT, ANDROID, SAFARI
}
public static WebElement fluentWait(WebDriver
driver,final By locator){
Wait<WebDriver> wait = new
FluentWait<WebDriver>(driver)
.withTimeout(30,
TimeUnit.SECONDS)
.pollingEvery(5,
TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
WebElement foo = wait.until(new
Function<WebDriver, WebElement>()
{
public WebElement apply(WebDriver
driver)
{
return
driver.findElement(locator);
}
}
);
return foo;
};
public static boolean verifyTextPresent(WebDriver
wd,String text)
{
return
wd.getPageSource().contains(text);
}
public static boolean WaitTextPresent(WebDriver
wd,String text)
{
int k=1;
boolean val1=false;
while(k !=0)
{
boolean
val=wd.getPageSource().contains(text);
if(val==true)
{
k=0;
val1=true;
}
else
{
wait(500);
k=1;
}
}
return val1;
}
}
|
Build.xml
|
<?xml
version="1.0" encoding="UTF-8"?>
<project
name="TestLink" default="exec" basedir=".">
<property name="src"
value="./src" /><!-- Change it to your source folder -->
<property name="project"
value="./TestProject" />
<property name="lib"
value="./lib" /><!-- Change it to your lib folder -->
<property name="bin"
value="./bin" /><!-- Change it to your bin folder -->
<property name="report"
value="./report" /><!-- Change it to your report folder
-->
<path id="test.classpath"><!--
Creating a classpath for use while compiling -->
<pathelement
location="${bin}" />
<fileset
dir="${lib}">
<include
name="**/*.jar" />
</fileset>
</path>
<target name="init"><!--
Initialization target which deletes and recreates the binary folder.-->
<delete dir="${bin}"
/>
<mkdir dir="${bin}"
/>
</target>
<!--Section1-->
<target name="compile"
depends="init"><!-- Target for compiling the source
folder -->
<javac source="1.7"
srcdir="${src};${project}" fork="true" destdir="${bin}"
>
<classpath>
<pathelement
path="${bin}">
</pathelement>
<fileset
dir="${lib}">
<include
name="**/*.jar" />
</fileset>
</classpath>
</javac>
</target>
<target name="exec"
depends="compile">
<delete
dir="${report}" />
<mkdir dir="${report}"
/>
<mkdir
dir="${report}/xml" />
<junit
printsummary="yes" haltonfailure="no">
<classpath>
<pathelement
location="${bin}" />
<fileset
dir="${lib}">
<include
name="**/*.jar" />
</fileset>
</classpath>
<formatter
type="plain"/>
<formatter
type="xml"/>
<batchtest fork="yes"
todir="${report}/xml">
<fileset
dir="${project}">
<include
name="**/*.java"/>
<exclude
name="**/TestProject_TCases.java"/>
</fileset>
</batchtest>
</junit>
<junitreport
todir="${report}"><!-- This section generated the Junit
report in html to "html" folder from the xml file. -->
<fileset
dir="${report}/xml">
<include
name="TEST*.xml" />
</fileset>
<report
format="frames" todir="${report}/html" />
</junitreport>
</target>
</project>
|
Hi Dhirendra,
ReplyDeleteIt was very helpful post.
Actually I am working on Python with Grid2 to run the test in parallel in FF, IE and Chrome browsers.
On FF test is executing successfully, can you please suggest how to set the "chromedriver" and "IEDriverServer.exe" path in Desire Capabilities to run the tests.
Appreciate your help!!
Thanks,
Atin
Hi Atin,
DeleteThanks for posting the comment. Please see below command line option and example script for using chromedriver and IEDriverServer -
Command Line for IE -> java -Dwebdriver.ie.driver="D:\\Applications\\IEDriverServer\\IEDriverServer.exe" -jar selenium-server-standalone-2.32.0.jar
Command Line for CHROME -> java -Dwebdriver.chrome.driver="D:\\Applications\\chromedriver\\chromedriver.exe" -jar selenium-server-standalone-2.32.0.jar
Example Script -
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
url = "http://:4444/wd/hub"
#driver = webdriver.Remote(command_executor = url, desired_capabilities = {'browserName':'ie'}) #for IE
driver = webdriver.Remote(command_executor = url, desired_capabilities = {'browserName':'chrome'}) #for chrome
driver.get("http://www.python.org")
assert "Python" in driver.title
elem = driver.find_element_by_name("q")
elem.send_keys("selenium")
elem.send_keys(Keys.RETURN)
assert "Google" in driver.title
driver.close()
Excelent workk!!! Thx
ReplyDeletePlease keep on posting articles on frame workk
Hi Dhirendra,
ReplyDeleteI have read the post word by word and line by line, very informative and you are my inspiration and roll modal. Thanks for spreading your knowledge and educate us and helping our life to be more technical.
Please keep on posting articles good articles.Thanks for sharing the post
ReplyDeleteFull Stack Training in Chennai | Certification | Online Training Course| Full Stack Training in Bangalore | Certification | Online Training Course | Full Stack Training in Hyderabad | Certification | Online Training Course | Full Stack Developer Training in Chennai | Mean Stack Developer Training in Chennai | Full Stack Training | Certification | Full Stack Online Training Course
This comment has been removed by the author.
ReplyDeletethanks for the post. It was very informative and useful.
ReplyDeletealso, check Python Classes in Pune