Wednesday, 21 March 2012

Example:Using CSSLocator with Selenium2 Webdriver API

Aim:To use CSS locators in place of Element locator and run with using Selenium 2 webdriver API.
Difficulty Level:Medium
Prerequisites:
  • Firefox and Selenium IDE installed
  • Firebug installed in Firefox.
  • Eclipse IDE
  • Selenium 2 API
Commands used in example:
  • Click
  • ClickAndWait
  • type
Example Steps:
  1. Open any already created script into Selenium IDE.
  2. Follow the video.
Expanded Steps:
  1. Open up Selenium IDE
  2. open up the sleenium script
  3. Run the selenium script in the IDE
  4. Notice that the selenium script ran successfully.
  5. Now aim is to replace the element locators with CSS Locators.
  6. Goto Selenium IDE and click on the third command "type, id=user_login", admin
  7. click on the input field next to Target and then press Find button
  8. Notice the button will blink yellow for two seconds
  9. now right click on the admin input field and click on "inspect element"
  10. the id=user_login >> becomes >> css=input#user_login
  11. copy the text and place it back into the selenium IDE script
  12. notice that teh selenium IDE script shows green to indiaccate that the css selector works
  13. Repeat this for the id=user_pass
  14. Repeat this for id=wp-submit >> becomes >> css=input[class='button-primary']
  15. Now Run the modified Selenium IDE script with the css selectors.
  16. Save the modified selenium IDE script 
  17. Now we want to run the modified script using Selenium Webdriver 2 api
  18. Click on "Export Test Case As" - > JUNIT 4 (Webdriver) and save/export
  19. now close down Selenium IDE
  20. Open up the saved exported java file in notepad ++
  21. Now Launch Eclipse IDE
  22. click on New-> Java Project and give name "CSSLocatorProject" and click Next and Finish
  23. Right click on SRC and select "package"
  24. give name "com.example.tests" and click Finish
  25. Right click package and create new class
  26. give name: CSSLocator and finish
  27. Copy the exported java file into this class file
  28. Now add the build path for Selenium Jar
  29. Right Click the project and select Build Path->configure build path
  30. click on Add External jars and  select the selenium jar file that you download from seleniumHQ ( selenium-server-standalone-2.24.1.jar)
  31. Notice the red errors disappear to indicate that the api has been loaded
  32. Notice that the code shows cssSelectors as a way to identify elements on the page
  33. Now Run the project - right click the class and select Run As Junit test
  34. the green indicates that the css selector script has successfully rin on Webdriver 2

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>http://foundation.time2test.co.uk/</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>clickAndWait</td>
<td>link=Posts</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 CSSLocator.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>http://foundation.time2test.co.uk/</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>clickAndWait</td>
<td>link=Posts</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>

Save the file as CSSLocator.java

package com.example.tests;

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class CSSLocator {
private WebDriver driver;
private String baseUrl="";
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}

@Test
public void testCSSLocator() throws Exception {
driver.get("http://foundation.time2test.co.uk/");
driver.findElement(By.linkText("Log in")).click();
driver.findElement(By.cssSelector("input#user_login")).clear();
driver.findElement(By.cssSelector("input#user_login")).sendKeys("admin");
driver.findElement(By.cssSelector("input[id='user_pass'][type='password']")).clear();
driver.findElement(By.cssSelector("input[id='user_pass'][type='password']")).sendKeys("time4test");
driver.findElement(By.cssSelector("input[class='button-primary']")).click();
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("MyFirstPost");
driver.findElement(By.id("publish")).click();
driver.findElement(By.cssSelector("[title='Log Out']")).click();
}

@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, 20 March 2012

Example: Integration of Selenium 2 with Maven

Aim:

Difficult Level: Medium

Prerequisits:
Steps to Implementation:
  1. Create the project directory "MavenProject".
  2. Create subdirectory "src".
  3. Create two subdirectory "testng" and "script" into "src" directory.
  4. Save the all below files to corresponding directory.
  5. Run the script use command: mvn install
Scripts:
  • Create file "pom.xml" under "MavenProject" directory.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.time2test</groupId>
<artifactId>Time2Text</artifactId>
<version>1.0.0</version>
<packaging>pom</packaging>
<name>Selenium Functional Tests</name>
<url>http://www.time2test.com/</url>


 <repositories>
<repository>
<id>openqa</id>
<name>OpenQA Repository</name>
<url>http://nexus.openqa.org/content/repositories/releases/</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
</repositories>

<dependencies>

<dependency>
 <groupId>junit</groupId>
 <artifactId>junit</artifactId>
 <version>4.4</version>        
</dependency>

 <dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.6.0</version>
</dependency>

   <dependency>
     <groupId>org.openqa.selenium.server</groupId>
     <artifactId>selenium-server</artifactId>
     <version>0.9.0</version>
   </dependency>

   <dependency>
     <groupId>org.seleniumhq.selenium.client-drivers</groupId>
     <artifactId>selenium-java-client-driver</artifactId>
     <version>1.0.2</version>
     <scope>test</scope>
   </dependency>

   <dependency>
     <groupId>org.testng</groupId>
     <artifactId>testng</artifactId>
     <version>5.7</version>
     <scope>test</scope>
     <classifier>jdk15</classifier>
   </dependency>
 </dependencies>

  <build>
     <testSourceDirectory>src/script</testSourceDirectory>
     <plugins>
       <!-- Compiler Plugin (support for JDK.5)-->
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-compiler-plugin</artifactId>
         <version>2.3.2</version>
    <executions>
           <execution>
             <goals>
               <goal>testCompile</goal>
             </goals>
           </execution>
         </executions>
         <configuration>
           <source>1.5</source>
           <target>1.5</target>
         </configuration>
       </plugin>

       <!-- Selenium Maven Plugin -->
       <plugin>
           <groupId>org.codehaus.mojo</groupId>
           <artifactId>selenium-maven-plugin</artifactId>
           <version>1.1</version>
           <configuration>
               <port>1247</port>
               <trustAllSSLCertificates>true</trustAllSSLCertificates>

           </configuration>
           <executions>
               <execution>
                   <phase>pre-integration-test</phase>
                   <goals>
                       <goal>start-server</goal>
                   </goals>
                   <configuration>
                       <background>true</background>
                   </configuration>
               </execution>
           </executions>
       </plugin>


       <!-- Surefire plugin -->
       <plugin>
         <groupId>org.apache.maven.plugins</groupId>
         <artifactId>maven-surefire-plugin</artifactId>
    <version>2.12</version>
         <executions>
           <execution>
             <phase>integration-test</phase>
             <goals>
               <goal>test</goal>
             </goals>
             <configuration>
               <skip>false</skip>
             </configuration>
           </execution>
         </executions>
         <configuration>
           <suiteXmlFiles>
             <suiteXmlFile>
               src/testng/testng.xml
             </suiteXmlFile>
           </suiteXmlFiles> 
           </configuration>
       </plugin>        
  
  </plugins>
</build>

</project>
  • Create file "testng.xml" file under "testng" directory.

<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="SeleniumWebdriverTests" parallel="tests">
<test name="WebdriverScriptWithMaven">
<classes>
<class name="com.example.tests.MavenExample" /> 
</classes>
</test>
</suite>
  • Create "MavenExample.java" file under "src/com/example/tests" directory.


package com.example.tests;

import com.thoughtworks.selenium.*;
import org.testng.annotations.*;
import static org.testng.Assert.*;
import java.util.regex.Pattern;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class MavenExample  {
private WebDriver driver;
private String baseUrl="http://foundation.time2test.co.uk/wp-login.php";
private StringBuffer verificationErrors = new StringBuffer();
@BeforeMethod
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.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();

}

@AfterMethod
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: