Sunday 21 October 2012

Avoid explicit delay in selenium


If you are using java with selenium for automation,then you should use explicit delay in your code(like Thread.sleep(2000)).

Here is an example for same:

WebDriverWait wait = new WebDriverWait(webDriver, 5);//here 5 is a maximum waiting time in seconds
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[@value='SignIn']")));

//ExpectedConditions have lot of functions for different actions,so use these functions according your requirement.

Mouse over on "element" using selenium



Here is is example of mouse over

Actions builder=new Actions(driver);
builder.moveToElement(tagElement).build().perform()

Saturday 20 October 2012

How to move cursor in selenium.



In automation testing,you need cursor movement for displaying hidden elements.

Here is a example:

public void mouseOverOnElement(WebElement tagElement)
{
try
{
Actions builder=new Actions(driver);
Point coordinate=tagElement.getLocation();
Robot robot=new Robot();
builder.moveToElement(tagElement, 5,5).build().perform();
builder.moveByOffset(1, 1).build().perform();
robot.mouseMove(coordinate.getX()+8,coordinate.getY()+60);

}
catch(Exception e)
{
logger.info("Error message in mouseOverOnElement method-->"+e);
}
}

Using the above code you are able to move mouse cursor.

Wednesday 17 October 2012

How to rerun failed testcases using testng.



If you want automatically rerun your failed testcases after completion,then use below approach:
Note:i think you know that whenever testcase is failed in testng,it creates a "testng-failed.xml" for failed testcases.

1)if you want to rerun automatically only failed testcases then you need modify pom.xml.
2) Run time you need to change testng.xml file path to "testng-failed.xml" in pom.xml.This you can do using any script language.I have done same using batch script.
Below is the batch script for same:

setlocal enabledelayedexpansion
set INTEXTFILE=pom.xml
set OUTTEXTFILE=pom_out.txt
set SEARCHTEXT=src/main/resources/testng.xml
set REPLACETEXT=target/failsafe-reports/testng-failed.xml
set OUTPUTLINE=

call mvn integration-test


for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A
SET modified=!string:%SEARCHTEXT%=%REPLACETEXT%!

echo !modified! >> %OUTTEXTFILE%
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

call mvn integration-test

for /f "tokens=1,* delims=¶" %%A in ( '"type %INTEXTFILE%"') do (
SET string=%%A
SET modified=!string:%REPLACETEXT%=%SEARCHTEXT%!

echo !modified! >> %OUTTEXTFILE%
)
del %INTEXTFILE%
rename %OUTTEXTFILE% %INTEXTFILE%

3) Now start execution using above batch file.

Tuesday 16 October 2012

How to handle CAPTCHA and certificates in selenium automation



If you are using firefox browser with selenium and you are facing captcha and certificates(for https traffic).
Then use same profile for handling captcha and certificate.

Refer the following link for "How to create a firefox profile".
http://seleniumproblemswithsolutions.blogspot.in/2012/10/how-to-create-profile-in-firefox-for.html

Now you can use same profile in webdriver using below code.
File f=new File("profile folder name");
FirefoxProfile firefoxProfile=new FirefoxProfile(f);
WebDriver driver = new FirefoxDriver(firefoxProfile);

How to create a profile in firefox for selenium.


If you are worried about how to handle CAPTCHA and firefox certificates.
Then use firefox profile for solving these problem.
Below are the steps for same.

1. Make sure all your firefox instance are closed
2. Click Start>Run
3. Type “firefox.exe -ProfileManager -no-remote”
4. Select “Create Profile” (i.e. selenium)
5. Click “Next”
6. Enter new profile name
7. Select a directory folder to store your new profile
8. Click “Finish”
9. Select “Don’t ask at startup”
10. Click “Start Firefox” and configure settings based on suggestion below***
11. Set Profile back to “default” (enable you to use your previous settings on your browser)
*** Suggested settings for your Selenium Profile
1. From “View\Toolbars” tab, uncheck “Bookmarks Toolbar”
2. Right click from toolbar and click “Customize”
3. Remove “Google search” by dragging it to the “Customize Toolbar” window
4. From the “Customize Toolbar” window, click “Use Small Icons” check box then hit “Done”
5. Click “Tools\Options” then set the following:
a. “Main” tab
- set Home Page to “about:blank”
- uncheck “Show the Downloads..” option
b. “Tabs” tab
- Select “a new window” for new pages
- Uncheck all warning options
c. “Content” tab
- uncheck “Block pop-up” windows option
d. “Privacy” tab
- uncheck all “History” options
e. “Security” tab
- uncheck all “Security” options
- click “Settings” and uncheck all warning options
f. “Advanced” tab
- Uncheck “autoscrolling” option from “General” tab
- uncheck “warn me …” and “Ssearch Engines”option from “Update” tab
7. From the address bar type “about:config” and add the following by right-click anywhere on the page and selecting “new”
- extensions.update.notifyUser (type=boolean; value=false)
- extensions.newAddons (type=boolean; value=false)

For more details refer following url:
http://kb.mozillazine.org/Creating_a_new_Firefox_profile_on_Windows

Saturday 13 October 2012

How to immediate rerun failed testcase using testng.


After developing a automation framework,now a automation tester want to reduce a false positive rate,so he/she will use immediate rerun of failed test case for reducing the failed test due to setup and network problem.

Below is the code for same:

1) Create a class with your rerun logic

Using the below logic you can immediate rerun your failed test case.
package com.companyName.web.utils;

import org.testng.IRetryAnalyzer;
import org.testng.ITestResult;

public class Retry implements IRetryAnalyzer{
private int retryCount = 0;
private int maxRetryCount = 3;
public boolean retry(ITestResult result) {

if(retryCount < maxRetryCount) { retryCount++; return true; } return false; } }

2) use below annotation in your test program
@Test(groups="groupName",retryAnalyzer=Retry.class)
if you are not using group then use this
@Test(retryAnalyzer=Retry.class)

Configured pom.xml file in maven project for selenium


How to configure pom.xml file in maven project for selenium.below is the code for same.
if you want to add more third party jar files then use dependency tag in pom.xml.
Mentioned some third party jar in below pom.xml

<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/xsd/maven-4.0.0.xsd">
<modelversion>4.0.0</modelVersion>
<groupid>MavenTest</groupId>
<artifactid>com.companyName.web.test</artifactId>
<version>0.0.1-SNAPSHOT</version>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
<plugins>
<plugin>
<groupid>org.apache.maven.plugins</groupId>
<artifactid>maven-surefire-plugin</artifactId>
<version>2.12</version>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<artifactid>maven-failsafe-plugin</artifactId>
<version>2.12</version>
<configuration>
<suitexmlfiles>

<suitexmlfile>${basedir}/src/main/resources/testng.xml</suiteXmlFile>
</suiteXmlFiles>
<skip>false</skip>
</configuration>
<executions>
<execution>
<goals>
<goal>test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupid>org.apache.maven.plugins</groupId>
<artifactid>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>


</plugins>
</build>

<dependencies>
<dependency>
<groupid>org.seleniumhq.selenium</groupId>
<artifactid>selenium-firefox-driver</artifactId>
<version>2.25.0</version>
</dependency>
<dependency>
<groupid>org.seleniumhq.selenium</groupId>
<artifactid>selenium-java</artifactId>
<version>2.25.0</version>
</dependency>
<dependency>
<groupid>org.seleniumhq.selenium</groupId>
<artifactid>selenium-server</artifactId>
<version>2.25.0</version>
</dependency>
<dependency>
<groupid>org.testng</groupId>
<artifactid>testng</artifactId>
<version>6.7</version>
</dependency>
<dependency>
<groupid>org.jsoup</groupId>
<artifactid>jsoup</artifactId>
<version>1.6.3</version>
</dependency>
<dependency>
<groupid>javax.mail</groupId>
<artifactid>mail</artifactId>
<version>1.4.5</version>
</dependency>
<dependency>
<groupid>mysql</groupId>
<artifactid>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
<dependency>
<groupid>log4j</groupId>
<artifactid>log4j</artifactId>
<version>1.2.17</version>
</dependency>   
<dependency>
<groupid>com.jcraft</groupId>
<artifactid>jsch</artifactId>
<version>0.1.44-1</version>
</dependency> 

</dependencies>
</project>


Friday 12 October 2012

How to get input data in your test program using Hashmap


In my last post,i described about,what are the technology we can use for a good and simple framework development.
Now you want to know about how to import input data in your test program,
So below are the code for same.
Note: you can arrange package structure according your requirement.

package com.companyName;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
import com.companyName.*;


public class Test {
String mystring []= new String [10000];
Map mMap = new HashMap();
//if you are using testng then use @BeforeSuite(alwaysRun=true) method and change below constructor to a simple java method.
Test()
{


String sPath=null;
String filename="inputfilename";//Tested with .csv file
int linenumber=0;
String[] temp;
StringTokenizer st = null;
try {
sPath = new java.io.File(".").getCanonicalPath();
System.out.println("Path: "+ sPath);

FileInputStream fileSt = new FileInputStream(sPath+"\\"+filename);
DataInputStream in = new DataInputStream(fileSt);

BufferedReader bufRdr = new BufferedReader(new InputStreamReader(in));
String line = "";
System.out.println("Path: "+ sPath+"\\"+filename);
while((line = bufRdr.readLine()) != null)
{

mystring[linenumber]=line;
TestDataObj TestDataObject = new TestDataObj() ;
System.out.println("Path: "+ sPath+"\\"+filename+TestDataObject);
temp=line.split(",");

System.out.println("Values-->"+temp[0]+"--"+temp[1]+"--"+temp[2]);
TestDataObject.setTestcaseID(temp[0]);
TestDataObject.setUserName(temp[1]);
TestDataObject.setPassword(temp[2]);

mMap.put(temp[0], TestDataObject);
//because temp[0] is a testcase id in my input file so i am using key value in hashmap.
linenumber++;

}
in.close();
}
catch(Exception e)
{

}

}

}

for setter and getter

package com.companyName;

public class TestDataObj {
private String sUserName=null;
private String sPassword=null;
private String sTestcaseID=null;
public String getUserName() {
return sUserName;
}
public void setUserName(String userName) {
this.sUserName = userName;
}
public String getPassword() {
return sUserName;
}
public void setPassword(String password) {
this.sPassword = password;
}

public String getTestcaseID() {
return sTestcaseID;
}
public void setTestcaseID(String testcaseid) {
this.sTestcaseID = testcaseid;
}

}
Test program

package com.companyName;

public class TestData {

public static void main(String args[])
{
Test test= new Test();
TestDataObj testobj=(TestDataObj)test.mMap.get("tc1");
System.out.println(testobj.getTestcaseID());
System.out.println(testobj.getUserName());
System.out.println(testobj.getPassword());
}

}

let me know if have any doubts.

Thursday 11 October 2012

How to develop simple and good framework for selenium automation.


Before starting any automation everybody wants a good framework with a good reporting mechanics.
There are lot of techies using you can develop a good framework.

Was develop framework using below tools/jars:
1) For input data:-Hash map,jxl and apache poi(third party jar),but my opinion use hash map,it is pretty easy and secure :)
Refer below link for hashmap:
http://letsdosomethingwithselenium.blogspot.in/2012/10/how-to-get-input-data-in-your-test.html
2) For build purpose:-Maven
Create a maven project using the eclipse(using the eclipse you can create a package structure easily) and configure pom.xml.
Refer the below link for configure pom.xml
http://letsdosomethingwithselenium.blogspot.in/2012/10/configured-pomxml-file-in-maven-project.html

3) For Unit test:-Testng
4) Log4j for logging purpose

So now you know that what are the tools,was used for selenium framework development.
I will describe it in my next post.






Sunday 7 October 2012

How to create a xpath in selenium


Xpath is language using we can get the element of the xml.

So probably you are thinking about how to create xpath using xpath language.

My point of view you should remember below mentioned point whenever you are creating xpath.

1) Always create short xpath.

2) Don’t use dynamic data(Like className,id.. etc) in xpath.

3) If you are feeling that your browser text(like button name ,link text,textbox text etc) are not changing frequently then you should use text only.

Like xpaths for link:-

//*[text()='SignIn']

//*[contains(text(),'Home')]

//*[starts-with(text(),"in your mind)]

for button:-

//*[@value='Login'] or //*[@*='Login']

etc

3) If same page having more than one xpath then use postion or create xpath depending upon the other text/control.

Like:-

//*[@*='Post'][position()=1]

if you want to access last button

//*[@*='Post'][position()=last()]

if all the button/links are getting displayed whenever you are using position=1 then use following xpath and mention postion according your requirment.

(//*[@*='Post'])[position()=3]

create xpath depending upon the other text/control:

//*[text()='Agent Page']/parent::*/parent::*/descendant::*[@*='Post']

for more details about the above mentioned functions refer following link http://www.w3.org/TR/xpath20/.

4) After creating xpath,verify same using xpath checker/firebug/xpather plugin.These are firefox plugin.

if above mentioned plugins are displaying same control as your browser.then your xpath is correct :-)