Test Automation some useful selenium hacks

Test Automation

Selenium Hacks- In this post I will be sharing some quick tips on selenium,Below are some of the code snippets that I mostly used when I am creating java test cases using selenium webdriver. I hope the same will help you save some time in your test script creation.

These tricky hacks are useful and make automation scripting effective, Tricks mentioned can be further optimized/updtaed as per requirement.

1-Capturing full page screenshot, with vertical scrollbar-

Using shutterbug jar full page screen capture can be done,It is capable of handling vertical, horizontal scrollbar effectively and captures a full screenshot.

String timeStamp = new SimpleDateFormat("HH_mm_ss").format(new Date());
String screenshot_timestamp = nullĀ  ;
screen_timestamp = screenshotname+"_"+timeStamp;
Shutterbug.shootPage(driver,ScrollStrategy.VERTICALLY).withName(screen_timestamp).save("Locl drive location");

2-Linking screenshot in TestNG reports-

To link captured a screenshot to testNg report below line of code can be called, this code link screenshot with click to open become hyperlink which opens captured screenshot.

Reporter.log("<a href="+"E:\\screenshot\\"+screenshot_timestamp+".png"+">click to open

3-Method to handle Sync Issues in web automation-

This is the best way to handle sync issues, by using a for loop with an upper limit of time

public WebElement Element_Finder(WebDriver driver, By locator, int T) throws InterruptedException
{
WebElement myElement = null;
//driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0));
for (int i = 1; i < T; i++)
{
try
{
System.out.println("Iteration -->"+ i);
myElement = driver.findElement(locator);
//This method is written in #4
WebElementHighlight(myElement, driver);
break;
}
catch (Exception ex)
{
Thread.sleep(1000);
System.out.println("Did not found element with locator"+locator);
}
}

4-Highlighting a web object with some colour-

Selenium driver will highlight the web object, we only need to call below method and same will highlight the web object in return

public void WebElementHighlight(WebElement element, WebDriver driver)
{
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("arguments[0].style.border='6px groove green'", element);
}
// return element;
}

5-Whether a webelement exist or not-

To identify whether a web element exists or not, below code is an effective way to identify the same.
In below code size of the webobject is being checked, where not equal to zero condition is being checked.

driver.findElements(By.id("element-id")).size()!=0

6-Working on frame-

While working on frames, first of all, identify the count of a frame and then use switch to method to switch over respective frame.


int i;
i=driver.findElements(By.xpath("//iframe")).size();
driver.switchTo().frame(i-1);

7-How to declare webdriver and use the same in another class-

Best way to declare a web driver in a class and then to get that driver.

Find below sample code

public class Superclass
{
public WebDriver driver;
public Superclass(){
driver = new FirefoxDriver();
}
public WebDriver getdriver(){
if (driver == null){
driver = new FirefoxDriver();
return driver;
}else{
return driver;
}
}
}

//In other class, call like below syntax
getdriver().findelement(by.xpath("xpath").click());

8- Integrating network sniffing with selenium scripts

Performance parameters for a single user can be determined by integrating, we can integrate sniffing tool called hTTPWatch with selenium. Refer this link

IT Automation-Integration of Selenium and Sniffing tool (HttpWatch)


for the same.

 

Groovy for counter start-

 

def myTestCase = context.testCase
propTestStep = myTestCase.getTestStepByName(“PropertyLooper”)
propTestStep.setPropertyValue(“ColumnCounter”,”1″)

 

groovy for Result Handling

// IMPORT THE LIBRARIES
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*

// DECLARE THE VARIABLES
def myTestCase = context.testCase //myTestCase contains the test case
def i=0,j=3
def Hlabel //header label for excel file
def Rdata = new Object[3] // Row Data
String[] Hdata = [“IntA”,”IntB”,”Result”]

//creating filename dynamically
def dataFolder = new com.eviware.soapui.support.GroovyUtils(context).projectPath // Get Project Path
def today = new Date().format(“yyyy-MM-dd”)
def filePrefix = “${dataFolder}/TestReports/TestCaseReport” as String
def fileNamePart = new Date().format(“yyyy-MM-dd’T’HH.mm.ss”)
def tcase = testRunner.testCase.getName()

// Setting Property as Dynamic File name to be used in later steps
propTestStep = myTestCase.getTestStepByName(“FileName”) // get the Property TestStep object
propTestStep.setPropertyValue(“FileName”,”${filePrefix}_${tcase}_${fileNamePart}.xls”)

// Writting Data Header data in File (File Name Created dynamically)
WritableWorkbook workbook1 = Workbook.createWorkbook(new File(“${filePrefix}_${tcase}_${fileNamePart}.xls”))
WritableSheet sheet1 = workbook1.createSheet(“Sheet1”,0)

while(i<=2)
{
Hlabel = new Label(i,0,Hdata[i])
sheet1.addCell(Hlabel)
i++
}

workbook1.write()
workbook1.close() //close the file

 

 

 

 

Groovy for Data source-

// IMPORT THE LIBRARIES WE NEED
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*

// DECLARE THE VARIABLES

def myTestCase = context.testCase //myTestCase contains the test case
def counter,next,previous,size //Variables used to handle the loop and to move inside the file

Workbook workbook1 = Workbook.getWorkbook(new File(“D:/SoapUI_calculator/IntA.xls”)) //file containing the data
Sheet sheet1 = workbook1.getSheet(0) //save the first sheet in sheet1
size = (sheet1.getRows().toInteger()) //get the number of rows, each row is a data set
propTestStep = myTestCase.getTestStepByName(“PropertyLooper”) // get the Property TestStep object
propTestStep.setPropertyValue(“IntA”,(size-1).toString())
counter = (propTestStep.getPropertyValue(“ColumnCounter”).toString()).toInteger() //counter variable contains iteration number

next = (counter > size-2?size:counter+1) //set the next value

// OBTAINING THE DATA YOU NEED

Cell f = sheet1.getCell(0,counter) // getCell(column,row)
//Cell t = sheet1.getCell(1,counter)

workbook1.close() //close the file

//the value is saved in the property

propTestStep.setPropertyValue(“IntA”,f.getContents())
//propTestStep.setPropertyValue(“TO”,t.getContents())

propTestStep.setPropertyValue(“ColumnCounter”, next.toString())
next++
propTestStep.setPropertyValue(“Next”, next.toString()) //set Next value on the properties step

//Decide if the test has to be run again or not
if (counter == size-1)
{
propTestStep.setPropertyValue(“StopLoop”,”T”)
}
else if (counter==0)
{
def runner = new com.eviware.soapui.impl.wsdl.testcase.WsdlTestCaseRunner(testRunner.testCase, null)
propTestStep.setPropertyValue(“StopLoop”,”F”)
}
else
{
propTestStep.setPropertyValue(“StopLoop”,”F”)
}

 

 

Groovy script for Result

 

// IMPORT THE LIBRARIES WE NEED
import com.eviware.soapui.support.XmlHolder
import jxl.*
import jxl.write.*

// DECLARE THE VARIABLES
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def dataFolder = groovyUtils.projectPath

def myTestCase = context.testCase //myTestCase contains the test case
def i=0
def label2
def Rdata = new Object[3]

propTestStep = myTestCase.getTestStepByName(“PropertyLooper”)
counter = (propTestStep.getPropertyValue(“ColumnCounter”).toString()).toInteger()

Rdata[0]= (propTestStep.getPropertyValue(“IntA”)).toString()
propTestStep.setPropertyValue(“IntA”,null)
Rdata[1]= (propTestStep.getPropertyValue(“IntB”)).toString()
propTestStep.setPropertyValue(“IntB”,null)
Rdata[2]= (propTestStep.getPropertyValue(“Result”)).toString()
propTestStep.setPropertyValue(“Result”,null)

 

// WRITING THE DATA

def FileName1 = testRunner.testCase.testSteps[‘FileName’].getPropertyValue(“FileName”)

Workbook workbook1 = Workbook.getWorkbook(new File(“${FileName1}”))
WritableWorkbook copy = Workbook.createWorkbook(new File(“${FileName1}”), workbook1);

WritableSheet sheet2 = copy.getSheet(0);

while(i<=2)
{
label2 = new Label(i,counter-1,Rdata[i])
sheet2.addCell(label2)
i++
}

copy.write()
copy.close()
workbook1.close() //close the file

 

 

Groovy Script for DataSource Loop

 

def myTestCase = context.testCase

def runner

propTestStep = myTestCase.getTestStepByName(“PropertyLooper”) // get the Property TestStep

endLoop = propTestStep.getPropertyValue(“StopLoop”).toString()

if (endLoop.toString() == “T” || endLoop.toString()==”True” || endLoop.toString()==”true”)
{
log.info (“DONE”)
//propTestStep.setPropertyValue(“ColumnCounter”,”1″)
assert true
}
else
{
testRunner.gotoStepByName(“Groovy Script for DataSource”) //setStartStep
}

Its Prashant Chaudhary, I have 10+ years of experience in software test automation, performance & process automation with various commercial and open source tools. This blog shares my experience on the topic of Automation. The content published on my blog is solely mine, it does not express the views of any of my employers (current or previous).
No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Selenium Basic
1
Step by step selenium – step 3, what is findelement method

Abstract- So far, we have learned how to launch a web browser, entering values in a text box and clicking button. In this post, we will learn about findelement method. Test automation is all about get and set, which means get from web and set into web. Talking more specifically- …

Test Automation
1
What is ITestListner interface and its Use in Selenium

There are several interfaces available in TestNG that allow you to modify TestNG’s behavior or to give test scripts additional strength. These interfaces are broadly called “TestNG Listeners”. Here are a few listeners which are commonly used: 1- IAnnotationTransformer 2- IAnnotationTransformer2 3- IHookable 4- IInvokedMethodListener 5- IMethodInterceptor 6- IReporter 7- …

Test Automation
How to Capture Screenshot in Selenium Webdriver-3 different ways

Abstract– Capturing screenshot is an essential feature of a test automation framework, They help in defect analyses once after test execution is over. In this blog post we will see how to capture screenshot, there are different ways to capture screenshots. Which includes- 1- Capture full Page 2- Capturng full …

Shares