Friday, January 29, 2016

Properties file Read/Write in Java

protected static Properties prop;
/**
* Method to load Property files
*
* @param filePath
* @return Properties
* @throws Exception
*/
public static Properties loadProperties(String filePath) throws Exception {
try {
prop = new Properties();
// Read object repository file
FileInputStream fis = new FileInputStream(new File(filePath));

// load all objects
prop.load(fis);
return prop;
} catch (Exception e) {
e.printStackTrace();;
}
return prop;

}

/**
* Method to get property valueF
*
* @param p
* -Properties
* @param name
* @return propValue
*/
public static String getProperties(Properties p, String name) {
String propValue = null;
try {
propValue = p.getProperty(name);
return propValue;
} catch (Exception e) {
e.printStackTrace();
}
return propValue;
}
 
/**
     * To set value into Property file
     *
     * @param prop
     * @param key
     * @param value
     */
    public void setProperty(Properties prop, String key, String value, String filePath) throws Exception {
        try {
            prop.setProperty(key, value);
            prop.store(new FileOutputStream(filePath), null);
        } catch (Exception e) {
          e.printStackTrace();
        }
    }
 
/**
     * Loading A Property File From The Classpath
     *
     * @param fileName
     *            - only file name without complete path
     * @throws Exception
     */
    public Properties loadPropertyFileFromClasspath(String fileName) throws Exception {
        try {
            if (fileName != null && !fileName.isEmpty()) {
                InputStream ins =  this.getClass().getClassLoader().getResourceAsStream(fileName);
                prop.load(ins);
            } else {
                throw new Exception("property file '" + fileName + "' not found in the classpath");
            }
        } catch (Exception e) {
            throw new Exception("Error while loadProperties: " + e.toString());
        }
        return prop;

    }

Monday, January 25, 2016

Capturing Page JavaScript Errors Using Selenium WebDriver


public void printPageErrors() throws Exception {
    //Capture all errors and store them In array.
    List Errors = JavaScriptError.readErrors(driver);
    System.out.println("Total No Of JavaScript Errors : " + Errors.size());
    //Print Javascript Errors one by one from array.
        for (int i = 0; i < Errors.size(); i++) {
            System.out.println("Error Message : " + Errors.get(i).getErrorMessage());
            System.out.println("Error Line No : " + Errors.get(i).getLineNumber());
            System.out.println(Errors.get(i).getSourceName());
            System.out.println();
        }
 }


Note: Need to download "JSErrorCollector-0.5.jar"
need to download "JSErrorCollector-0.5.jar"

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");