Saturday, January 23, 2016

How To Get X Y and Height Width Coordinates Of Element In Selenium WebDriver


public void getCoordinates() throws Exception {
 //Locate element for which you wants to retrieve x y coordinates.
    WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
    //Used points class to get x and y coordinates of element.
    Point point = Image.getLocation();
    int xcord = point.getX();
    System.out.println("Element's Position from left side Is "+xcord +" pixels.");
    int ycord = point.getY();
    System.out.println("Element's Position from top side Is "+ycord +" pixels.");
 }

public void getSize() throws Exception {
//Locate element for which you wants to get height and width.
    WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
    //Get width of element.
    int ImageWidth = Image.getSize().getWidth();
    System.out.println("Image width Is "+ImageWidth+" pixels");
    //Get height of element.
    int ImageHeight = Image.getSize().getHeight();
    System.out.println("Image height Is "+ImageHeight+" pixels");
 } 

How To Handle Stale Element Reference Exception in Selenium Webdriver

public boolean retryingFindClick() {
boolean result = false;
 int count = 0;
// It will try 2 times to find same element using name.
    while (count < 2) {
         try {
                //If exception generated that means It Is not able to find element
               //then catch block will handle It.
               WebElement webEle = driver.findElement(By.name("name"));
               //If exception not generated that means element found
               //and element text get cleared.
              webEle.click();
              result = true;
              break;
         } catch (StaleElementReferenceException e) {
                System.out.println("Trying to recover from a stale element :"
                                                 + e.getMessage());
         }
          count++;
    }
    return result;
}

Wednesday, December 16, 2015

Updating testng xml at runtime


import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.WebDriver;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.xml.XmlClass;
import org.testng.xml.XmlSuite;
import org.testng.xml.XmlTest;
public class WebdriverITestListener implements ITestListener {
boolean ischecked=true;
public static XmlSuite suite ;
@Override
public void onFinish(ITestContext arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailedButWithinSuccessPercentage(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestFailure(ITestResult test) {
// TODO Auto-generated method stub
}
@Override
public void onTestSkipped(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onTestStart(ITestResult test) {
// TODO Auto-generated method stub
String browserName=test.getMethod().getXmlTest().getParameter("browserName");
if(ischecked)
{
List tests = new ArrayList();
XmlTest testsuite = new XmlTest(test.getMethod().getXmlTest().getSuite());
testsuite.setName("defalut");

List xmlclasses = new ArrayList();
xmlclasses.add(new XmlClass("TESTCASE NAME"));

testsuite.addParameter("browserName","firefox");
testsuite.setXmlClasses(xmlclasses);
tests.add(testsuite);
suite.setTests(tests);
test.getMethod().getXmlTest().setXmlSuite(suite);
ischecked=false;
}
System.out.println(test.getMethod().getXmlTest().getSuite()+"  ------------------   ");
WebDriver driver;
try {
driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onTestSuccess(ITestResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStart(ITestContext test) {
- hide quoted text -

}
}

Thursday, December 10, 2015

TestNG Parallel Execution

  • Methods: This will run the parallel tests on all @Test methods in TestNG.
  • Tests: All the test cases present inside the <test> tag will run with this value.
  • Classes: All the test cases present inside the classes that exist in the XML will run in parallel.

package com.parallel;
import org.testng.annotations.Test;

public class TestParallelOne {

    @Test
    public void testCaseOne() {
        //Printing Id of the thread on using which test method got executed
        System.out.println("Test Case One with Thread Id:- "
                + Thread.currentThread().getId());
    }

    @Test
    public void testCaseTwo() {
        ////Printing Id of the thread on using which test method got executed
        System.out.println("Test Case two with Thread Id:- "
                + Thread.currentThread().getId());
    }
}

Running test methods parallelly in TestNG using Selenium
http://testng.org/testng-1.0.dtd">
<suite name="Parallel test suite" parallel="methods" thread-count="2">
  <test name="Regression 1">
    <classes>
      <class name="com.parallel.TestParallelOne"/>
    </classes>
  </test>
</suite>

Running tests parallelly in TestNG using Selenium

<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite" parallel = "tests" thread-count = "2">
   <test name = "Parallel Tests1">
      <classes>
        <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
   <test name = "Parallel Tests2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
 Running test classes parallelly in TestNG using Selenium
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd" >
<suite name = "Parallel Testing Suite">
   <test name = "Parallel Tests" parallel = "classes" thread-count = "2">
      <classes>
         <class name="com.parallel.TestParallelOne"/>
         <class name="com.parallel.TestParallelOne"/>
      </classes>
   </test>
</suite>
   
 

Tuesday, October 27, 2015

Delete files in a Directory?

/**
     * Delete file
     *
     * @param filePath
     */
    public void deleteFile(String filePath) throws Exception {
        try {
            File file = new File(filePath);

            if (file.delete()) {
                System.out.println(file.getName() + " is deleted..!");
            }
        } catch (Exception e) {
            throw new Exception(">>>Error while deleting " + filePath + " file :<<<" + e.toString());
        }
    }
 
public void deleteFilesFromFolder(File directoryPath) {
        String[] myFiles;
        if (directoryPath.isDirectory()) {
            myFiles = directoryPath.list();
            for (int i = 0; i < myFiles.length; i++) {
                File myFile = new File(directoryPath, myFiles[i]);
                myFile.delete();
            }
        }
    }

EX: File directoryPath = new File("C:\\Example");

Thursday, September 10, 2015

Using log4j in Java Program

public static Logger logger_name = Logger.getLogger(classname.class);

PropertyConfigurator.configure(System.getProperty("user.dir") + "\\config\\log4j.properties");

EX:
public static Logger APP_LOGS = Logger.getLogger(DriverScript.class.getName());

log4j.properties:

# Define the root logger with appender file
log = TestOutput/Logs
log4j.rootLogger = INFO, FILE
# log4j.rootLogger = INFO,console, FILE ( To print all logging messages to both the console and a log file)

# Define the file appender(RollingFileAppender OR ConsoleAppender(to print in console))
log4j.appender.FILE=org.apache.log4j.RollingFileAppender
log4j.appender.FILE.File=${log}/SFDCTests.html

# Constrole the maximum log file size
log4j.appender.FILE.maxFileSize=10000KB

# Archive log files (one backup file here)
log4j.appender.FILE.maxBackupIndex=3

# Define the layout for file appender
(HTMLLayout OR PatternLayout)
log4j.appender.FILE.layout=org.apache.log4j.HTMLLayout
log4j.appender.FILE.layout.Title=Logger For SFDC Test Cases
log4j.appender.FILE.layout.LocationInfo=true

#do not append the old file. Create a new log file everytime
log4j.appender.FILE.Append=false
 
#Prevent internal log4j DEBUG messages from polluting the output.
#log4j.logger.org.apache.log4j.PropertyConfigurator=INFO
#log4j.logger.org.apache.log4j.config.PropertySetter=INFO
#log4j.logger.org.apache.log4j.FileAppender=INFO
 

Friday, September 4, 2015

Right Click Function With Selenium Webdriver



public void RightClickAndChooseAnOption()
    {
               
        WebElement oWE=driver.findElement(By.linkText("About Google"));
       
        Actions oAction=new Actions(driver);
        oAction.moveToElement(oWE);
        oAction.contextClick(oWE).sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).build().perform();
       
    }