Sunday, 4 December 2011

how to install eclipse IDE?

Aim: How to install eclipse IDE?

Steps:
  • Go to page "http://www.eclipse.org/downloads/
  • Download the "Eclipse IDE for java Developers" using "Windows 32bit" link
  • After downloading save the Zip at the appropriate place
  • Unzip it
  • Open the Eclipse folder
  • Click 'eclipse', see the eclipse icon below.
  • Eclipse IDE interface would be opened.

Wednesday, 30 November 2011

Where to download jUnit and how to install?

Aim:Where to download jUnit and how to install?

Key Steps:
  1. For download the Junit jar use URL: https://github.com/KentBeck/junit/downloads
  2. Open the Eclipse IDE.
  3. Create JAVA project directory.
  4. Select the Project and right click
  5. Click 'Properties' option.
  6. Select 'Java build path' and click 'Add External Jar' button.
  7. Select the downloaded Jar file.
  8. Click 'OK' button.
  9. Successfully added the jar file with the created Project.
Helpful Video:

Where to download testNG and how to install?

Aim:Where to download testNG and how to install?

Key Steps:
  1. For download the Selenium Standalone server use URL:http://testng.org/doc/download.html
  2. Extract the downloaded zip file.
  3. Open the Eclipse IDE.
  4. Create JAVA project directory.
  5. Select the Project and right click.
  6. Click 'Properties' option.
  7. Select 'Java build path' and click 'Add External Jar' button.
  8. Select the downloaded Jar file.
  9. Click 'OK' button.
  10. Successfully added the jar file with the created Project.
Helpful Video:

Where to download Selenium Server standalone jar from?

Aim:Where to download Selenium Server standalone jar from?

Key Steps:
  1. For download the Selenium Standalone server use URL:http://code.google.com/p/selenium/downloads/list
  2. Open the Eclipse IDE.
  3. Create JAVA project directory.
  4. Select the Project and right click.
  5. Click 'Properties' option.
  6. Select 'Java build path' and click 'Add External Jar' button.
  7. Select the downloaded Jar file.
  8. Click 'OK' button.
  9. Successfully added the jar file with the created Project.
Helpful Video:

How to check that JDK is installed and working?

Aim:How to check that JDK is installed and working?

Key Steps:
  1. Download the JDK from URL: http://www.oracle.com/technetwork/java/javase/downloads/index.html
  2. Installed the downloaded JDK installer.
  3. Set the path of bin directory of JDK into System variable.
  4. Set the JAVA_HOME variable of JDK folder into System variable.
  5. For check the working of JDK,open the command prompt.
  6. Execute the command 'java -version'.
  7. In message version is displayed of JDK.

Helpful Video:

How to check that Ant is installed and working?

Aim: How to check that Ant is installed and working?

Key Steps:
  1. Download the Ant tool from URL: http://ant.apache.org/
  2. Put the downloaded zip file into anywhere in the System.
  3. Extract the downloaded zip file.
  4. Set the path of bin directory of Ant tool into System variable.
  5. For check the working of Ant tool,open the command prompt.
  6. Execute the command 'ant -version'
  7. In message version is displayed of Ant .

Helpful Video:

Thursday, 24 November 2011

Example - Selenium Grid2

Aim - To demonstrate how to run multiple tests on multiple browsers (IE and FF) in parallel using Selenium Grid2. The Selenium scripts which are written in java will open up Google.com and Search for the keywords.

Difficulty Level: HIGH

Pre-requisites:

  • JDK (JAVA version "1.6.021") should be installed and working
  • Ant (Apache Ant version 1.7.1) should be working
  • selenium-server-standalone-2.12.0.jar
  • testng-5.14.1.jar

Wednesday, 9 November 2011

Example : Working with dbunit using junit

Aim:
To demonstrate DBunit with Junit by inserting a record in the database then using dbunit to assert for the uploaded records in a database/ table.

Difficulty Level: High

Pre-Requisites:
  • Eclipse IDE installed
  • MY SQL Server should be installed and working
  • dbunit, junit, java mysql connector jar files available
Steps involved in implementation:
  • Create a database / table using My sql database server
  • Connect with created database's table using java My SQL connection code
  • In the connected table upload records through XML file using DBunit methods
  • The XML shows the number of records we have uploaded into the table
  • With the help of dbunit methods we assert for the uploaded records in table

Friday, 21 October 2011

Example-Cross Browser Testing

Aim:To run the Script on different browser.
Difficulty Level: High

Prerequisites:
  • Eclipse IDE installed
  • selenium-grid-tools, selenium java client driver. jar from http://seleniumhq.org/download/
  • Selenium RC server
  • Firefox,Chrome and IE installed
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, name, linkText,cssSelector
  • clear()
  • sendkeys()
  • click()
  • random string
Steps in implementation:
  1. Create a Java Project in Eclipse IDE.
  2. Now copy the script and save as CrossTest.java
  3. Include all the jar files with the created project.
  4. Start Selenium RC Server via command line.
  5. For running the same test we need to just change the driver like below script is for the Firefox driver and will run on same, so just running the script on IE, we need to load the IE browsers driver
  6. For IE ->
    IWebDriver driver = new InternetExlorerDriver();
  7. For Google Chrome ->
    IWebDriver driver = new ChromeDriver();
  8. See the Result

Example - Data driven test using a csv text file

Aim:Data driven example using CSV ( Comma Separated Variable) file and Selenium 2. The example demonstrates adding new posts to the wordpress test site via the csv file. Test data data can be added to the csv file.


Difficulty Level: High

Prerequisites:
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, linkText, cssSelector and xpath
  • clear()
  • sendkeys()
  • click()
  • random string
Steps in implementation:
  1. Download and Install Eclipse IDE using link http://www.eclipse.org/downloads/.     
  2. Tip: download the version suitable for your PC ( 32 bit/64bit))
  3. Download the Selenium2 API 'selenium-server-standalone-*.jar' library using link http://seleniumhq.org/download
  4. No need to get JUnit jar file in separate as it is inbuilt in  'selenium-server-standalone-*.jar'.
  5. Download and save the file as selenium.csv in C: drive from here
  6. Launch the Eclipse IDE.
  7. Create a new Java project and name it FirstExample. You will see a default folder 'src' inside it.
  8. Do right click on the created project and select Build Path >> Configuration Build Path.
  9. Add 'selenium-server-standalone-*.jar' under Libraries tab by clicking 'Add External Jars'.
  10. Add downloaded "javacsv-2.0.jar"  under Libraries tab by clicking 'Add External Jars'.
  11. Right click on 'src' and add a package 'com.example.tests'.
  12. Create  java classes  'DataDriven.java ' into the created package.
  13. Paste the below mentioned two script in corresponding java files.
  14. Right click 'DataDriven.java' and click 'Run as >> JUnit test'.
  15. During the execution you would see that created post title is read from the CSV file.

Thursday, 20 October 2011

FirstExample - Selenium 2 using WebDriver API

Aim:Example to demonstrate Selenium 2 using Webdriver API.
Difficulty Level: High


Prerequisites:
  1. Eclipse IDE installed
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, name, link text, css and xpath
  • IsElementPresent()
  • clear()
  • sendkeys()
  • click()
  • random string
  • assertTrue()
  • getEval()
Steps in implementation:
  1. In first step, created a Java Project directory On Eclipse IDE.
  2. In second step. copy all the scripts and save as .java formate.
  3. Downloaded Selenium 2 Library.
  4. Included all the downloaded libraries with the project’s directoryaccording to video.
  5. Run the scripts successfully.

Scripts:
Save as Suite.java
package com.example.tests;
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Suite {
private WebDriver driver;
private String baseUrl="http://foundation.time2test.co.uk/";
public StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testSuite() throws Exception {
Login ln=new Login(driver);
ln.loginAs();
PostBlog post=new PostBlog(driver);
post.newPost();
AddUser user=new AddUser(driver);
user.newUser();
}
@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

}


Save as Login.java
package com.example.tests;
import org.openqa.selenium.*;
import org.testng.Assert;
import com.thoughtworks.selenium.Selenium;

public class Login {
private WebDriver driver;
public Login(WebDriver driver) {
this.driver = driver;
}
public void loginAs() {
driver.get("http://foundation.time2test.co.uk/");
Selenium selenium = new WebDriverBackedSelenium(driver, "http://foundation.time2test.co.uk/");
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
Assert.assertTrue(selenium.isTextPresent("Username"));
Assert.assertTrue(selenium.isTextPresent("Password"));
driver.findElement(By.id("user_login")).sendKeys("admin");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("time4test");
driver.findElement(By.id("wp-submit")).click();
try{
Thread.sleep(3000);
}catch(Exception e){}
}
}

Save as AddUser.java
package com.example.tests;
import org.openqa.selenium.*;
import com.thoughtworks.selenium.Selenium;
import java.util.*;


public class AddUser {
private WebDriver driver;
public AddUser(WebDriver driver) {
this.driver = driver;
}
public void newUser() throws Exception
{
driver.findElement(By.linkText("Users")).click();

Random rand = new Random();
int numNoRange = rand.nextInt();
String userstr="TestNewUser"+numNoRange;
String email="Testemail"+numNoRange+"@yahoo.com";
driver.findElement(By.xpath("//li[@id='menu-users']/div[3]/ul/li[2]/a")).click();

driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys(userstr);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(email);

driver.findElement(By.id("first_name")).clear();
driver.findElement(By.id("first_name")).sendKeys("TestFirst");
driver.findElement(By.id("last_name")).clear();
driver.findElement(By.id("last_name")).sendKeys("TestLast");
driver.findElement(By.id("url")).clear();
driver.findElement(By.id("url")).sendKeys("http://www.google.com/");
driver.findElement(By.id("pass1")).clear();
driver.findElement(By.id("pass1")).sendKeys("time2test");
driver.findElement(By.id("pass2")).clear();
driver.findElement(By.id("pass2")).sendKeys("time2test");
driver.findElement(By.id("addusersub")).click();
DeleteUser del=new DeleteUser(driver);
del.delUser(userstr);
}

}

Save as DeleteUser.java
package com.example.tests;

import org.openqa.selenium.*;
import com.thoughtworks.selenium.*;
import org.openqa.selenium.WebElement;

public class DeleteUser {
private WebDriver driver;
public DeleteUser(WebDriver driver) {
this.driver = driver;
}
public void delUser(String user) throws Exception
{
Selenium seleniumDriver = new WebDriverBackedSelenium(driver, "http://foundation.time2test.co.uk/");
driver.findElement(By.cssSelector("a.wp-first-item.current")).click();
driver.findElement(By.id("user-search-input")).clear();
driver.findElement(By.id("user-search-input")).sendKeys(user);
driver.findElement(By.cssSelector("input.button")).click();
driver.findElement(By.xpath("//div[@id='wpwrap']/div[@id='wpcontent']/div[@id='wpbody']/div[@id='wpbody-content']/div[3]/form[@id='posts-filter']/table/thead/tr/th[@id='cb']/input")).click();
WebElement element = driver.findElement(By.name("action"));
/*seleniumDriver.select("name=action", "label=Delete");
seleniumDriver.click("id=doaction");
seleniumDriver.waitForPageToLoad("30000");
*/

element.sendKeys("Delete");
driver.findElement(By.id("doaction")).click();
driver.findElement(By.name("submit")).click();
}

}



Save as PostBlog.java
package com.example.tests;
import org.openqa.selenium.*;
import com.thoughtworks.selenium.Selenium;


public class PostBlog {
private WebDriver driver;
public PostBlog(WebDriver driver) {
this.driver = driver;
}
public void newPost()throws Exception
{
Selenium selenium = new WebDriverBackedSelenium(driver, "http://foundation.time2test.co.uk/");
driver.findElement(By.linkText("Posts")).click();
try{
Thread.sleep(3000);
}catch(Exception e){}

driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).clear();
selenium.type("id=title", selenium.getEval(""Post" + new Date().getMilliseconds();"));
driver.findElement(By.id("publish")).click();
driver.findElement(By.cssSelector("a.wp-first-item.current")).click();
}

}




Helpful Video:

Example-CSS Locators

Aim:To use CSS locators in place of Element locator.
Difficulty Level:Easy
Prerequisites:
  • Firefox and Selenium IDE installed
  • Firebug installed in Firefox.
Commands used in example:
  • Click
  • ClickAndWait
  • type
  • waitForElementPresent
  • assertTextPresent
Steps:
  1. Open any already created script into Selenium IDE.
  2. Follow the video.
Find out more
http://santoshsarmajv.blogspot.co.uk/2012/04/webelements-locators.html

Script:Save the file as Script.html
<span style="font-weight: bold;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://foundation.time2test.co.uk/" />
<title>Script</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Script</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>/</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log in</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=user_login</td>
<td>admin</td>
</tr>
<tr>
<td>type</td>
<td>id=user_pass</td>
<td>time4test</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=wp-submit</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>//div[@id='user_info']/p/a[2]</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Posts</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>Dashboard</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Add New</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=title</td>
<td>MyFirstPost</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=publish</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log Out</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
</span>


Save the file as CSSLocatorScript.html
<span style="font-weight: bold;"><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="http://foundation.time2test.co.uk/" />
<title>Script</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">Script</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>/</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Log in</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>css=input#user_login</td>
<td>admin</td>
</tr>
<tr>
<td>type</td>
<td>css=input[id='user_pass'][type='password']</td>
<td>time4test</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>css=input[class='button-primary']</td>
<td></td>
</tr>
<tr>
<td>waitForElementPresent</td>
<td>//div[@id='user_info']/p/a[2]</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Posts</td>
<td></td>
</tr>
<tr>
<td>assertTextPresent</td>
<td>Dashboard</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>link=Add New</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>id=title</td>
<td>MyFirstPost</td>
</tr>
<tr>
<td>clickAndWait</td>
<td>id=publish</td>
<td></td>
</tr>
<tr>
<td>clickAndWait</td>
<td>css=[title='Log Out']</td>
<td></td>
</tr>
</tbody></table>
</body>
</html>
</span>

Helpful Video:

Wednesday, 19 October 2011

Example - Selenium 2 with Junit

Aim:Example to demonstrate Selenium 2 using JUnit

Difficulty Level:High
Prerequisites:
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, name, link text, css and xpath
  • IsElementPresent()
  • clear()
  • sendkeys()
  • click()
  • capture screen shot
  • store value
  • random string
Covered Test Cases list:
  • Login into the Wordpress content management application.
  • Creating a new user.
  • Asserting that if new user is created or not.
  • verify if Comments page is available into the application.
  • Verify if user is able to post.
  • Check if user's post is exist into the application.
  • Verify if user is able to create a new page.
  • Check if created page does exist into the application.
  • Verify that user is able to add a link into the application.
  • Check if added links exist into the application.
  • verify if user is able to add a new category.
  • Check if added categories exist into the application.
  • Verify if user is able to add a new Media.
  • Check if added Media exists into the application.

Steps:
  1. Use the IDE to record a simple script
  2. convert into Junit/Webdriver Formatted Code using the IDE
  3. Save the code in java Formate.
  4. Launch Eclipse
  5. Create a Java project directory, see the attached video file for how to create Java project in Eclipse
  6. Move saved java file to the project directory
  7. Now include the Selenium 2 API jars and JUnit jar with the created Project.
  8. Run the Project
  9. See the Result
  10. All screen shot would saved into C:\\tmp folder path
Learn more:
Junit - http://www.roseindia.net/junit/writingandtesting.shtml


Script:
Save as Selenium2Example.java

package com.example.tests;

import java.io.File;
import java.util.Random;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.junit.*;
import static org.junit.Assert.*;

import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Selenium2Example {
private WebDriver driver;
private String baseUrl="http://foundation.time2test.co.uk/";
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void test() throws Exception {
driver.get(baseUrl);
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys("admin");
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys("time4test");
driver.findElement(By.id("wp-submit")).click();

// Creating a new user in Word press
driver.findElement(By.linkText("Users")).click();
driver.findElement(By.cssSelector("a.button.add-new-h2")).click();
driver.findElement(By.id("user_login")).clear();
int a=new Random().nextInt(123456789);
String User_name= "testuser"+a;
driver.findElement(By.id("user_login")).sendKeys(User_name);
driver.findElement(By.id("email")).clear();
String Email_address= "testemail"+a+"@gmail.com";
driver.findElement(By.id("email")).sendKeys(Email_address);
driver.findElement(By.id("first_name")).clear();
driver.findElement(By.id("first_name")).sendKeys("Word");
driver.findElement(By.id("last_name")).clear();
driver.findElement(By.id("last_name")).sendKeys("Press");
driver.findElement(By.id("url")).clear();
driver.findElement(By.id("url")).sendKeys("http://www.test.com");
driver.findElement(By.id("pass1")).clear();
driver.findElement(By.id("pass1")).sendKeys("123-asd");
driver.findElement(By.id("pass2")).clear();
driver.findElement(By.id("pass2")).sendKeys("123-asd");
driver.findElement(By.id("addusersub")).click();
driver.findElement(By.cssSelector("input.button")).click();

//Verify the created user via screenshot...

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\tmp\\user.png"));

// Adding post in Word press
driver.findElement(By.linkText("Posts")).click();
File scrFile1 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
//Verify the open post list via screenshot...
FileUtils.copyFile(scrFile1, new File("c:\\tmp\\Post.png"));
driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).clear();
// generating random values and using the same
String postname= "testpost"+a;
// below command is used for the Echo purpose, if we have the random value in to the variable or no
driver.findElement(By.id("title")).sendKeys(postname);

// Using wait for element present function below
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.id("publish"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}

// finding element by xpath
driver.findElement(By.xpath("//input[@id='publish']")).click();

// Creating a new page in word press
driver.findElement(By.linkText("Pages")).click();

driver.findElement(By.cssSelector("a.button.add-new-h2")).click();
driver.findElement(By.id("title")).clear();
String Page_name= "tespage"+a;
driver.findElement(By.id("title")).sendKeys(Page_name);
driver.findElement(By.id("publish")).click();
//Verify the created page via screenshot...
File scrFile2 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile2, new File("c:\\tmp\\Page.png"));
driver.findElement(By.linkText("Pages")).click();
driver.findElement(By.id("post-search-input")).clear();
// Searching for the created page if it's added or not
driver.findElement(By.id("post-search-input")).sendKeys(Page_name);
driver.findElement(By.cssSelector("p.search-box > input.button")).click();

// Working with Links page
driver.findElement(By.linkText("Links")).click();
driver.findElement(By.cssSelector("a.button.add-new-h2")).click();
driver.findElement(By.id("link_name")).clear();
String Test_link= "teslink"+a;
driver.findElement(By.id("link_name")).sendKeys(Test_link);
driver.findElement(By.id("publish")).click();
//Verify the created link via screenshot...
File scrFile3 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile3, new File("c:\\tmp\\Links.png"));
// adding a new category
driver.findElement(By.linkText("Link Categories")).click();
driver.findElement(By.id("link-name")).clear();
String Test_category= "teslinkcategory"+a;
driver.findElement(By.id("link-name")).sendKeys(Test_category);
driver.findElement(By.name("submit")).click();
driver.findElement(By.id("link-category-search-input")).clear();
driver.findElement(By.id("link-category-search-input")).sendKeys(Test_category);
driver.findElement(By.cssSelector("input.button")).click();

// Navigating Media page
driver.findElement(By.linkText("Media")).click();
driver.findElement(By.cssSelector("a.button.add-new-h2")).click();
//Verify the created Media page via screenshot...
File scrFile4 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile4, new File("c:\\tmp\\Media.png"));

driver.findElement(By.linkText("Log Out")).click();
// going to capture screen shot of the logout screen
File scrFile5 = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile5, new File("c:\\tmp\\screenshot.png"));
}

@After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}

private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}

Helpful Video:

Tuesday, 18 October 2011

Example: Selenium and TestNG framework

Aim:To create java selenium Scripts using a IDE and execute them in TestNg Framework.

Difficulty level:Medium
What you will learn?
  • How to switch from IDE to TestNg Framework
  • Basics of the TestNg Framework Setup
  • Introduction to the build.xml
Tips:
  • Basic idea of Selenium IDE
  • Basic knowledge of Java
  • Basic knowledge of Ant
Pre-requisites:
  • Firefox and Selenium IDE installed  http://www.mozilla.org/en-US/firefox/new/
  • Download Ant package from http://ant.apache.org/. You will get a zip file.
  • Extract Ant package zip file in some place for example "C:\".
  • Set 'C:\apache-ant-*\bin' in environment path.
  • Create a new environment variable 'ANT_HOME' and provide it value 'C:\apache-ant-*'.
  • Download 'selenium-server-standalone-*.jar' from http://seleniumhq.org/download/
  • download testng.jar from http://testng.org/doc/download.html. Follow TestNG install
  • Install TestNG plugin into Eclipse. (This is required if you want to run TestNG scripts from Eclipse)
  • Open Eclipse IDE, click 'Help >> Install New Software'.
  • Write 'http://beust.com/eclipse' in 'Work With' field and save this with name as 'TestNG'.
  • Select 'TestNG' checkbox and finish installation of plugin.
Screenshot showing the directory structure:
















Commands used in example:
  • click()
  • waitForPageToLoad()
  • type()
  • start()
  • open()
  • stop()
Exercise Steps:
  1. Open Eclipse and create a java project i.e. TestNgProject.
  2. Create package 'com.example.tests' inside the project.
  3. Right click on project name and click 'New >> Folder' with name 'lib'.
  4. Put all the downloaded jar files into lib directory.
  5. Create a new java class under newly created package with name 'QuickTest.java' and paste code from below mentioned java script.
  6. Right click on project name and click 'Build Path >> Configure Build Path'.
  7. Select all jar files from project's 'lib' folder under 'libraries' tab.
  8. Right click on project name and click 'New >> File' with name 'build.properties'.
  9. Right click on project name and click 'New >> File' with name 'build.xml'.
  10. Right click on project name and click 'New >> Folder' with name 'config'.
  11. Right click on 'config' and click 'New >> File' with name 'single.xml'
  12. Start Selenium - open command prompt, go to the path where selenium-server-standalone is, and execute the command "java -jar selenium-server-standalone-*.jar" (replace * with version). 
  13. Execute the created Project via Ant tool -  open command prompt, go to the path upto project root folder, execute command "ant".
  14. See the Result

Conclusions
  • TestNg Framework and see it working with a java selenium Example
  • Familiar with end to end advanced Selenium Script Design for TestNg Framework.
  • Familiar with how to record a script using Selenium IDE and convert it to Java
Script: save the below code in build.properties file under TestNgProject folder. Replace the ws.home value as per your system path.

ws.home=D:/workspace/TestNGProject
test.dest=${ws.home}/bin 
test.src=${ws.home}/src
save the below code in build.xml in TestNgProject folder



<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE project [
]>

<project name="S4" default="all" basedir=".">

<!-- ========== Initialize Properties =================================== -->
<property environment="env"/>
<property file="./build.properties"/>

<!-- Deletes the existing classes and report directory-->

 <target name="clean">
  <delete dir="{test.dest}" />
 </target>

 <!-- Creates the  build, docs and dist directory-->

 <target name="makedir" depends="clean">
  <mkdir dir="${test.dest}" />
 </target>
 
 <!--Create a classpath container which can be later used in the ant task-->

 <path id="test.classpath">
  <pathelement location="${test.dest}" />

  <fileset dir="${ws.home}/lib">
   <include name="**/*.jar"/>
  </fileset>
 </path>

 <!-- Compiles all the java files (including the usage of library for JUnit -->

 <target name="compile" depends="makedir">
  <javac srcdir="${test.src}" destdir="${test.dest}">
   <classpath refid="test.classpath" />
  </javac>
 </target>

 <taskdef name="testng" classpathref="test.classpath" classname="org.testng.TestNGAntTask" />

<!-- run -->

<target name="single" depends="compile">
<testng classpath="${test.classpath}:${test.dest}" suitename="SingleTestExecution">
<xmlfileset dir="${ws.home}/config" includes="single.xml"/>
</testng>
</target>


<target name="all" depends="single">
<echo>
ant run will execute the test
</echo>
</target>

</project>


save the following code in single.xml

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5"  verbose="1" name="SingleTestExecution" annotations="JDK">
<test name="Search_Book" junit="false">
<classes>
<class name="com.example.tests.QuickTest">
 <methods>
  <include name="testQuickTest" />
 </methods>
</class>
</classes>
</test>
</suite>

save the following code in QuickTest.java

package com.example.tests;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.regex.Pattern;

public class QuickTest extends SeleneseTestCase {
public DefaultSelenium selenium;


@BeforeMethod
public void startSelenium(){
selenium = new DefaultSelenium("localhost", 4444, "*chrome","http://foundation.time2test.co.uk/");
selenium.start();
selenium.open("http://foundation.time2test.co.uk/");
}

@AfterMethod
public void tearDown() throws Exception {
selenium.stop();
}
@Test public void testQuickTest() throws Exception {
selenium.open("/");
selenium.click("link=Log in");
selenium.waitForPageToLoad("30000");
selenium.type("id=user_login", "admin");
selenium.type("id=user_pass", "time4test");
selenium.click("id=wp-submit");
selenium.waitForPageToLoad("30000");
selenium.click("link=Posts");
selenium.waitForPageToLoad("30000");
selenium.click("link=Add New");
selenium.waitForPageToLoad("30000");
selenium.type("id=title", "This is new Post");
selenium.click("id=publish");
selenium.waitForPageToLoad("30000");
selenium.click("link=Log Out");
selenium.waitForPageToLoad("30000");

}
}


Helpful Video:




Video details:
1. in this video , we are going to record a Selenium IDE script and change it into JAVA code and then run on the TestNG Framework
2. OPen up Selenium IDE
3. click on Red Record Button to record a script
4. navigate to foundation.time2test.co.uk
5. Login using admin/time4test
6. Click on "add new"
7. Enter Title for post and click publish
8. Save the test case as "quicktest.html"
9. Now convert the .html into JAVA format
10. in Selenium IDE , goto File->Export Test Case As...->TestNG (remote Control)
11. Save the file as "quicqtest.java"
12. We have already created a Project Directory based on TestNG framework
D:\TestNGProject\
bin\
config\
Single.xml - contains xml entry to quicktest.java
lib\
selenium-server-standalone-*.jar
testng-*.jar

test\
Quicktest.java - pre-created test framework
build properties file - contains ws.home
build.xml
13. Now copy the test method in the recorded/converted script into \test\quicktest.java
14. now open single.xml and ensure that class name and method name as per the java file
15. Now open build.xml and match up the target name
16. Start the selenium server
17. open up new command prompt
18. cd d:\TestNgProject\
19. enter command >ant single
20. notice the selenium script execute
21. Goto Test-output directory
22. open up the results file
23. Green indicates that the script ran successfully.

Monday, 17 October 2011

Example: First selenium script from End to End

Aim:
To create java selenium Scripts using a IDE and execute them in Eclipse in less than 10 steps. Here we are using the IDE to create java code which is different from using webdriver which a richer and more flexible api.

Difficulty level: Medium

What you will learn?
  • How to switch from IDE to Selenuium RC using Java
  • Basics of the advanced IDE Eclipse Setup
  • Introduction to the Selenium Java Client Driver
  • Introduction to JUnit Api
Tips:
  • Basic idea of Selenium IDE
  • Basic knowledge of Java.
Pre-requisites:
  • Eclipse installed
  • Selenium RC server
  • Firefox and Selenium IDE installed
  • add the jar files to eclipse
Commands used in example:
  • start()
  • open()
  • click()
  • waitForPageToLoad()
  • isTextPresent()
  • assertTrue()
  • type()
  • isElementPresent()
  • getEval()

Exercise Steps:
1. Use the IDE to record a simple script
2. convert into Junit/Java Formatted Code using the IDE
3. Save the code QuickTest.java on the harddrive
4. Launch Eclipse
5. Create a Java project directory, see the attached video file for how to create Java project in Eclipse
6. Move QuickTest.java to the project directory
7. Start Selenium RC Server via command line
8. Execute QuickTest.java via JUnit
9. See the Result


Conclusions
  • Installed Ecplise IDE and seen it working with a java selenium Example
  • Familiar with end to end advanced Selenium Script Design
  • Familiar with how to record a script using Selenium IDE and convert it to Java

Solution:
See the java code below after converting the recorded HTML script in IDE to Junit:
package com.example.tests;

import com.thoughtworks.selenium.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.regex.Pattern;

public class QuickTest extends SeleneseTestCase {
@Before
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://foundation.time2test.co.uk/");
selenium.start();
}

@Test
public void testQuick() throws Exception {
selenium.open("/");
selenium.click("link=Log in");
selenium.waitForPageToLoad("30000");
assertTrue(selenium.isTextPresent("Username"));
assertTrue(selenium.isTextPresent("Password"));
selenium.type("id=user_login", "admin");
selenium.type("id=user_pass", "time4test");
selenium.click("id=wp-submit");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("//div[@id='user_info']/p/a[2]")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

selenium.click("link=Posts");
selenium.waitForPageToLoad("30000");
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (selenium.isElementPresent("//div[@id='wpbody-content']/div[3]/h2")) break; } catch (Exception e) {}
Thread.sleep(1000);
}

selenium.click("link=Add New");
selenium.waitForPageToLoad("30000");
selenium.type("id=title", "MyPost");
selenium.click("id=publish");
selenium.waitForPageToLoad("30000");
selenium.click("link=Users");
selenium.waitForPageToLoad("30000");
assertTrue(selenium.isTextPresent("Users"));
selenium.click("//li[@id='menu-users']/div[3]/ul/li[2]/a");
selenium.waitForPageToLoad("30000");
selenium.type("id=user_login", selenium.getEval(""Testuser" + new Date().getMilliseconds();"));
selenium.type("id=email", selenium.getEval(""Testemail" + new Date().getMilliseconds()+"@gmail.com";"));
selenium.type("id=first_name", "TestFirst");
selenium.type("id=last_name", "TestLast");
selenium.type("id=url", "http://www.google.com/");
selenium.type("id=pass1", "time2test");
selenium.type("id=pass2", "time2test");
selenium.click("id=addusersub");
selenium.waitForPageToLoad("30000");
selenium.click("link=Log Out");
selenium.waitForPageToLoad("30000");
}

@After
public void tearDown() throws Exception {
selenium.stop();
}
}

Helpful Video:


Example - Page Object Model example

Aim:
This example will demonstrate the Page Object Model technique which allows for better script  maintenance and reduces code duplication. This type of  framework allows the scripts to be less "brittle"

Difficulty Level:Medium

Prerequisites:
  • Eclipse IDE installed
  • Selenium 2/Webdriver API.
Commands used in example:
  • Driver.manage()
  • Driver.get(baseUrl)
  • Driver.findElement by id, name, linkText, css Selector and xpath
  • clear()
  • sendkeys()
  • click()
  • random string
Steps:

  1. Download and Install Eclipse IDE using link http://www.eclipse.org/downloads/
  2. Tip: download the version suitable for your PC ( 32 bit/64bit))
  3. Download the Selenium2 API 'selenium-server-standalone-*.jar' library using link http://seleniumhq.org/download
  4. No need to get JUnit jar file in separate as it is inbuilt in  'selenium-server-standalone-*.jar'.
  5. Launch the Eclipse IDE
  6. Create a new Java project and name it FirstExample. You will see a default folder 'src' inside it.
  7. Do right click on the created project and select Build Path >> Configuration Build Path
  8. Add 'selenium-server-standalone-*.jar' under Libraries tab by clicking 'Add External Jars'.
  9. Right click on 'src' and add a package 'com.example.tests'.
  10. Create 4 java classes  'postPage.java', ' AddUser.java', 'loginPage.java' and 'DisplayNewsTest.java' into the created package.
  11. Paste the below mentioned 4 scripts in corresponding java files.
  12. Right click 'DisplayNewsTest.java' and click 'Run as >> JUnit test'.

Also See:

http://code.google.com/p/selenium/wiki/PageObjects
http://stackoverflow.com/questions/466819/how-can-i-make-my-selenium-tests-less-brittle
http://stackoverflow.com/questions/7997858/page-object-model-best-practices-in-selenium

What did you learn?

  1. the usage of page object modelling ( Page object model) framework
  2. makes you think about script maintenance 



Scripts:

Save the code as DisplayNewsTest.java

package com.example.tests;

import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;


public class DisplayNewsTest {
 private WebDriver driver;
 public String baseUrl="http://foundation.time2test.co.uk/";
 private StringBuffer verificationErrors = new StringBuffer();
 @Before
 public void setUp() throws Exception {
  driver = new FirefoxDriver();
  driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }
  @Test
  public void testDisplayNewsTest() throws Exception {
   LoginPage loginPage = new  LoginPage(driver);
   PostPage dashboard = loginPage.loginAs("admin", "time4test");
   AddUser newsPage = dashboard.goToNewPage();
    newsPage.NewDisplayed();
   }
  @After
  public void tearDown() throws Exception {
   driver.quit();
   String verificationErrorString = verificationErrors.toString();
   if (!"".equals(verificationErrorString)) {
    fail(verificationErrorString);
   }
  }

}

Save the code as LoginPage.java
package com.example.tests;
import org.openqa.selenium.*;
public class LoginPage {

private WebDriver driver;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public PostPage loginAs(String userName,String password) {
driver.get("http://foundation.time2test.co.uk/");
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys(userName);
driver.findElement(By.id("user_pass")).clear();
driver.findElement(By.id("user_pass")).sendKeys(password);
driver.findElement(By.id("wp-submit")).click();
return new PostPage(driver);
}
}


Save as PostPage.java
package com.example.tests;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;

public class PostPage {
private WebDriver driver;
public PostPage(WebDriver driver) {
this.driver = driver;
}
public AddUser goToNewPage() {
driver.findElement(By.linkText("Posts")).click();

driver.findElement(By.linkText("Add New")).click();
driver.findElement(By.id("title")).clear();
driver.findElement(By.id("title")).sendKeys("MyPost");
driver.findElement(By.id("publish")).click();
return new AddUser(driver);
}

}


Save as AddUser.java
package com.example.tests;
import org.openqa.selenium.By;
import java.util.*;

import org.openqa.selenium.WebDriver;

public class AddUser {
private WebDriver driver;

public AddUser(WebDriver driver) {
this.driver = driver;
}

public void  NewDisplayed()throws Exception {
driver.findElement(By.linkText("Users")).click();

driver.findElement(By.xpath("//li[@id='menu-users']/div[3]/ul/li[2]/a")).click();
Random rand = new Random();
int numNoRange = rand.nextInt();
String userstr="TestNewUser"+numNoRange;
String email="Testemail"+numNoRange+"@yahoo.in";
driver.findElement(By.id("user_login")).clear();
driver.findElement(By.id("user_login")).sendKeys(userstr);
driver.findElement(By.id("email")).clear();
driver.findElement(By.id("email")).sendKeys(email);

driver.findElement(By.id("first_name")).clear();
driver.findElement(By.id("first_name")).sendKeys("TestFirst");
driver.findElement(By.id("last_name")).clear();
driver.findElement(By.id("last_name")).sendKeys("TestLast");
driver.findElement(By.id("url")).clear();
driver.findElement(By.id("url")).sendKeys("http://www.google.com/");
driver.findElement(By.id("pass1")).clear();
driver.findElement(By.id("pass1")).sendKeys("time2test");
driver.findElement(By.id("pass2")).clear();
driver.findElement(By.id("pass2")).sendKeys("time2test");
driver.findElement(By.id("addusersub")).click();
driver.findElement(By.linkText("Log Out")).click();
}
}



Helpful Video:

Wednesday, 21 September 2011

Robotium tool integration with TestDroid

Aim:
To create a script via TestDroid tool and run the created script using Robotium.

Difficulty Level: Hard

What you will learn?
How to run script into the Android emulator using integration of EclipseIDE, TestDroid and Robotium.


Questions?

  1. What is TestDroid?
  2. What is Robotium?

Tips:

  • Good knowledge of EcpliseIDE



Wednesday, 24 August 2011

How to ensure that Android set-up in EclipseIDE is correct?

KeySteps:
  • Open the Eclipse IDE and validate if Android setup is installed.
  • Click on Window menu.
  • Check if Android SDK and AVD Manager as menu option is displayed.
  • Click on Android SDK and AVD Manager menu option.
  • Click on Installed packages option.
  • All installed packages are displayed.
  • Click on File menu.
  • Click on New->project icon.
  • Android option is displayed.

How to install Android-server-xxx.apk file into Android Virtual Device?

Key Steps:
  • Open the URL http://code.google.com/p/selenium/downloads/list
  • Download the Android-server.x.x.x.apk file here x.x.x denotes any version.
  • Put the downloaded Android-server-x.x.x.apk file into platform-tool directory of installed Android SDK (C:\Documents and Settings\Administrator\android-sdks\platform-tools).
  • Open the Eclipse IDE.
  • Create and launch a new Android Virtual Device(AVD).
  • Open the command-prompt and select the platform-tool directory.
  • Execute the command ‘adb install android-server-xxx.apk’.
  • Re-launch AVD to make the created changes.
  • Android-Server is successfully installed into AVD.