Wednesday, July 15, 2015

After a tedious work of framing testcases in TestNG class based on priority, if a situation arise to add a test case in between any of those test methods, it will lead you to an annoyed situation of incrementing priorities of all the test methods below the newly inserted test case. I had faced such a situation. Not understood? don't worry, I will give you a sample code to make you understand where I was halted.

import org.testng.annotations.Test;
public class testNGPriorityExample {
 @Test(priority=1)
 public void registerAccount()
 {
  System.out.println("First register your account");
 }
 @Test(priority=2)
 public void sendEmail()
 {
  System.out.println("Send email after login");
 }
 @Test(priority=3)
 public void login()
 {
  System.out.println("Login to the account after registration");
 }
} 
Here I wanted to add a test method after register account. After inserting the test method, I was required to increment priority of all the following test methods. In my case there were many methods required to be incremented which is not an easy task. So I searched for a solution and finally found the annotation transformer listener which helped me.

Here I am giving the listener code which you have to include in your project.

package testpackage;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import org.testng.IAnnotationTransformer;
import org.testng.annotations.ITestAnnotation;

public class PriorityAnnotationTransformer implements IAnnotationTransformer
{
    static ClassPool s_ClassPool = ClassPool.getDefault();

    @Override
    public void transform(ITestAnnotation p_annotation, Class p_testClass, Constructor p_testConstructor, Method p_testMethod)
    {
        p_annotation.setPriority(getMethodLineNumber(p_testMethod));
    }
    private int getMethodLineNumber(Method p_testMethod)
    {
        try
        {
            CtClass cc = s_ClassPool.get(p_testMethod.getDeclaringClass().getCanonicalName());
            CtMethod methodX = cc.getDeclaredMethod(p_testMethod.getName());
            return methodX.getMethodInfo().getLineNumber(0);       
        }
        catch(Exception e)
        {
            throw new RuntimeException("Getting of line number of method "+p_testMethod+" failed", e);
        }
    }
}
Below is the testng.xml format required.

<?xml version="1.0" encoding="UTF-8"?>
<suite name="Customer" parallel="false">
<listeners>
    <listener class-name="testpackage.Transformer"/>
</listeners>
<test name="Test1">
   <classes>
      <class name="testpackage.Testclass"/>
    </classes>
  </test> <!-- Test -->
  </suite> <!-- Suite -->

Thursday, June 11, 2015

 
















                           In automation testing , date selection is an important area you can never miss. Every date widget will have an input field where text input are accepted. So most of the times as a workaround, we tries to code accordingly to enter the date manually. But it's very important to automate the selection of date from the widget because there may be scenarios in which date widget may not work properly. Here, I will show you a piece of code to automate the date selection from the widget.

public void selectdob(String day, String month, String year){
            //To popup date widget
            new WebDriverWait(BrowserConf.driver, 10).until(
                    ExpectedConditions.presenceOfElementLocated(By.xpath(obj
                            .getProperty("dobbutton")))).click();
            //To select the year from dropdown
            Select yeardrop= new Select(new WebDriverWait(BrowserConf.driver, 10).until(
                    ExpectedConditions.presenceOfElementLocated(By.className(obj
                            .getProperty("yearclass")))));
            yeardrop.selectByVisibleText(year);
            //To select the month from dropdown
            Select monthdrop= new Select(new WebDriverWait(BrowserConf.driver, 10).until(
                    ExpectedConditions.presenceOfElementLocated(By.className(obj
                            .getProperty("monthclass")))));
            monthdrop.selectByVisibleText(month);
            //To select the date from the table
            WebElement table_element = BrowserConf.driver.findElement(By.className("ui-datepicker-calendar"));
            List<WebElement> tr_collection=table_element.findElements(By.xpath("id('ui-datepicker-div')/table/tbody/tr"));
            //System.out.println("NUMBER OF ROWS IN THIS TABLE = "+tr_collection.size());
            int row_num,col_num;
            row_num=1;
            for(WebElement trElement : tr_collection)
            {
                List<WebElement> td_collection=trElement.findElements(By.xpath("td"));
                //System.out.println("NUMBER OF COLUMNS="+td_collection.size());
                col_num=1;
                for(WebElement tdElement : td_collection)
                {
                    if(tdElement.getText().equals(day)){
                        tdElement.click();
                    }
                    col_num++;
                }
                row_num++;
            }
        }

And you can now call the above function as:

selectdob("24","Jul","2012");

 First two statements are used for selecting month and year from the dropdown in the widget of my application. You may need to have slight change if the widget is different. Last part for selecting the date will be the same.



Thursday, June 4, 2015

In this article, I will be showing you how to fetch and update data of database using JDBC. You may operate any database using the required driver of the particular database

For an example I have used connection to H2 database. H2 has both embedded and server mode. I have tried the server mode. In server mode concurrent connections can be possible.

Prerequisites:
1. Eclipse IDE, Luna or any older version
2. JDK 8 or any older
3. Download Windows installer of H2 database and install to any folder in Windows. You will find a jar file like h2-1.3.176.jar. Copy the file to the library folder of your project and import the JAR.

Now you have done the initial configuration. What you need to do now is create a database in H2.

Double click the h2.bat file in the bin folder of the H2 folder in the installed location. It will load in your default browser. Select the H2 Generic H2 (Server) in first drop down. Give a name in second field. Copy the driver class to a notepad. Create a url in JDBC url field like jdbc:h2:tcp://ipaddress/~/test. Save this to the notepad.

Open Eclipse now. Create a Java class to code the JDBC connection part.

JDBC Class
package datpackage;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
import org.h2.tools.Server;

/**
 * @author www.javaworkspace.com
 *
 */
public class jdbcclass {
    public static ResultSet resultSet = null;
    public static Connection connection = null;
    public static Statement statement = null;
    public static Server server;
    public static void query(String sql) {       
        try {
            Class.forName("org.h2.Driver");
           
            try{
                connection = DriverManager.getConnection("jdbc:h2:tcp://ipaddres/~/test", "sa", "");
                   
            }
           catch(SQLException e2){
               e2.printStackTrace();
               return;   
               
           }
            statement = connection.createStatement();
           
            try{
                resultSet= statement.executeQuery(sql);
               
            }
        catch(SQLIntegrityConstraintViolationException e1){
            java.awt.Toolkit.getDefaultToolkit().beep();
            return;   
        }
            while (resultSet.next()) {
                System.out.println(resultSet.getString("NAME"));
            }
        } catch (SQLException e2) {
            e2.printStackTrace();
            return;   
            } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(resultSet!=null){
                resultSet.close();
                statement.close();
                connection.close();
                }
               
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    public static void update(String sql){
        try {
            Class.forName("org.h2.Driver");

            try{
                connection = DriverManager.getConnection("jdbc:h2:tcp://ipaddres/~/test", "sa", "");
            }
            catch(SQLException e2){
                e2.printStackTrace();
                return;   

            }
            try {
                statement = connection.createStatement();
                statement.executeUpdate(sql);
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }  catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
                connection.close();
                server.stop();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
You can now call statements in a different class to fetch and update data.

 To fetch data:
jdbcclass.query("SELECT * FROM H2DATABASE  NAME WHERE NAME LIKE A% ORDER BY NAME");

To update data:
jdbcclass.update("INSERT INTO H2DATABASE VALUES ('"Abc"', '"bcd"','"efg"');");




Sunday, May 24, 2015

This time we have got a useful lesson for Selenium Aspirants. It is "Parallel execution of Selenium tests using Selenium grid". Advantages of using Selenium Grid are:

1) To execute tests on different browsers, to test the cross browser compatibility of the application.
2) To cut down the time taken for executing tests because  the whole test can be divided in to small segments and executed parallel.

How to use Selenium Grid:

Prerequisites:
1) Download the Selenium Standalone Server Jar file, click here.
 2) Eclipse IDE, JDK any version, TestNG plugin installed

Procedure:
1) Make few batch files to create a hub, nodes.
2) Double click on the batch file to create hub
3) Run the batch file for node from a different machine, provided the browser version is matching
 4) Once the hub and node are created, you may execute the tests.


Here are the links of batch file for creating hub and node:

  • For batch file to create hub, click here
  • For Firefox node, click here
  • Internet explorer node, click here
Create a hub in one machine, nodes in another machines, so while running tests each tests will run corresponding to the node.

 Code for running the test:

 public class WebDriverGrid2Test {

public WebDriver driver;
Customerfunctions cf;
@Parameters({"browser", "version", "os","loginname","password"})
@BeforeClass
public void setup(String browser, String version, String os,String username, String password) throws MalformedURLException,     InterruptedException {
DesiredCapabilities capability=null;
capability = gridStting(browser, version, os);
driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), capability);
driver.navigate().to("url");
cf= new Customerfunctions(driver);
cf.setlogin(username,password);
try {
    cf.setup();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
}
@Test(priority='1')
public void testlogin() throws InterruptedException{
Thread.sleep(3000);
cf.login();
}
@Test(priority='2')
public void menunavigate(){
cf.menuselection();
}
@AfterClass
public void tearDown(){       
driver.quit();
}
public DesiredCapabilities gridStting(String browser, String version, String os){
DesiredCapabilities capability=null;
if(browser.equals("firefox")){
System.out.println("Test scripts running on firefox");
capability= DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setVersion(version);
}
if(browser.equals("iexplore")){
System.out.println("Test scripts running on iexplore");
capability= DesiredCapabilities.internetExplorer();
capability.setBrowserName("iexplore");
System.setProperty("webdriver.internetexplorer.driver", "lib\\IEDriverServer.exe");
capability.setVersion(version);
}
if(os.equals("WINDOWS")){
capability.setPlatform(org.openqa.selenium.Platform.WINDOWS);
}
else if(os.equals("XP")){
capability.setPlatform(org.openqa.selenium.Platform.XP);
}
else if(os.equals("Linux")){
capability.setPlatform(org.openqa.selenium.Platform.LINUX);
}
else{
capability.setPlatform(org.openqa.selenium.Platform.ANY);
}
return capability;
}
  }


Format of testng.xml for running Selenium node.

 <?xml version="1.0" encoding="UTF-8"?>
 <suite name="Test case run on Two environment" parallel="tests"> 
      <test name="Run on Internet Explorer">
          <parameter name="browser"  value="iexplore"/>
           <parameter name="version"  value="8"/>
           <parameter name="os"  value="WINDOWS"/>
           <parameter name="loginname"  value="loginname"/>
           <parameter name="password"  value="password"/>
            <classes>
                <class name="maypackage.WebDriverGrid2Test"/>
            </classes>
        </test>
         <test name="Run on Firefox">
              <parameter name="browser"  value="firefox"/>
              <parameter name="version"  value="29.0"/>
              <parameter name="os"  value="WINDOWS"/>
              <parameter name="loginname"  value="loginname"/>
           <parameter name="password"  value="password"/>
               <classes>
                  <class name="maypackage.WebDriverGrid2Test"/>
               </classes>
          </test>
 </suite>


Tuesday, March 31, 2015

I decided to create a graphical user interface for our framework because it may ease our script execution job and also enhance the functionality of the test framework by having the ability to run with any input test case file without the need of editing the XML everytime. A graphical interface in our case evolved with the use of selecting the input TC file. Later I added the feature to show the results of test execution as well as duration taken for the test operation. A test framework if exported to a runnable JAR file, it is easier for any user to execute this.
In this post I will give you a brief idea how to install Window Builder Pro plugin in Eclipse. After the installation of WindowBuilder Pro, you can develop UI by drag and drop elements required.

Download WindowBuilder Pro plugin:
You may download from the below link

Click here



Select the link as shown in above screenshot.

How to install WindowBuilder plugin in Eclipse:

First open Eclipse, click Help->Install new Software



Click Add, select the Archive from the saved location





Select all options and finish



If you are done with the installation, we shall start the development of user interface.

Create a new Java class, Expand Window builder, then expand Swing Designer and select Jframe, Click Next, Finish.







Now the Jframe class is created, it will have two portions, Source and Design.

Click Design to add UI components. Just for sample, drag a JTextfield and Jbutton from Palette chooser to the frame on right.



Select Jbutton, Right click and add an Action eventhandler- Actionperformed






Click on Action peformed. Now switch to source part. Add below code inside the action performed:

textField.setText(“Button pressed”);


Now save(Ctrl+S) and run as Java application, you will see the UI opening up. Click on the button, observe











Hope these steps will help you to design one yourself.....

Sunday, March 29, 2015

If you are looking for a solution to automate files drag and drop and Adobe flash content in Selenium, you are in the right page. In this post I will familiarize you about Sikuli. Sikuli automates anything you see on the screen. It uses image recognition to identify and control GUI components. It is useful when there is no easy access to a GUI's internal or source code.


About Sikuli:
Sikuli is an open-source research project originally started at the User Interface Design Group at MIT.

How to setup sikuli in Selenium

It's quite simple. You have to download Sikuli_setup.jar from Sikuli project page. Here is the link to download Sikuli. Click here.





Once the download is finished, copy the jar file to any folder. Click the sikuli-setup.jar to start the setup process. Once you double click the JAR file, you will observe two extra files been created, a batch file and a log file. 



Click the prompt shown for your information and proceed. Next, you will observe a screen with few options. To automate using Sikuli along with Selenium in Eclipse, you need to select Options 1,4,6 only.




 Click okay to proceed. Once the setup is finished, you will get two JAR files sikuli-ide.jar and sikuli-java.jar. One is the Sikuli IDE and other is library file you need to add in eclipse project library to write sikuli scripts in eclipse.

Setup environmental variables for Sikuli

You need to add a system environmental variable %SIKULI_HOME%




Since all setup is finished, we may proceed with scripting. Hope you have added Sikuli library file in Eclipse. Now create a java class for Sikuli and write script as below. You may call this method whenever required.

Code for flash automation:
package newpackage;

import org.sikuli.script.FindFailed;
import org.sikuli.script.Screen;


public class Photocapture{
public static Screen screen;
public static void saveimage() throws FindFailed, InterruptedException{
screen =new Screen();
Thread.sleep(1000);
screen.click("images/allowcamera.png");
Thread.sleep(5000);
screen.click("images/captureimage.png");
Thread.sleep(2000);
screen.click("images/saveimage.png");
Thread.sleep(2000);
}

}

Like this you may use functions for drag and drop files. All you need is the image of source file and image of target.

In order to drag and drop files, use below statement:

screen.dragDrop("source image path", "target image path");

Always remember Sikuli automation will work when the given image is visible in your screen.

 I would like to thank Sikuli project team for their wonderful work :)

Friday, March 27, 2015

There are two methods out of which first one is preferrable:

Method1:

First you have to get the Select element of the dropdown using below statement
Select dropdown = new Select(
new WebDriverWait(driver, 10).until(ExpectedConditions
.presenceOfElementLocated(By.id("elementid"))));


Then using the Select element you get, you can select the dropdown value by using any of the below statement


dropdown.selectByVisibleText("dropdownvalue");
or
dropdown.selectByIndex(0);
or
dropdown.selectByValue("value");


Method2:

List<WebElement> dd= new ArrayList<WebElement>();
dd = new WebDriverWait(driver, 10).until(ExpectedConditions.presenceOfElementLocated(By.id("elementid")))
.findElements(By.tagName("option"));
for (WebElement option : dd) {
//System.out.println(option.getText());
if (outname.equalsIgnoreCase(option.getText())){
option.click();
break;
}
}

Method 1 is more preferrable in Selenium webdriver. However in PhantomJS I found first method is not working. So try method 2 in such cases.

Wednesday, March 25, 2015

There are mainly two types:  Implicit Waits and Explicit waits

Implicit Wait

Implicit wait tells webdriver to poll for a specific amount of time. Once the time is over, WebDriver object will expire.

 Explicit Wait

Explicit wait tells the WebDriver to wait for certain conditions to occur before proceeding. By using WebDriverWait in combination with ExpectedCondition we can accomplish this.

Explicit wait are of two types:  WebDriver Wait and Fluent wait

WebDriver Wait:

Check below code:


Webelement element=null;
try{
element= new WebDriverWait(driver, 10).until( ExpectedConditions.presenceOfElementLocated(By.id(“elementid”))))
element.click();
}
catch (TimeoutException toe){

}

Once the wait is over and still the element is not found, it will throw a Timeout exception. So try to code inside a try/catch statement.


Fluentwait:

Webdriver wait is an extension of Fluentwait. In Fluentwait it also specifies the pollingtime to check for the condition of element ignoring nosuchElement exceptions.

Check below code:
 
try {
        new FluentWait<WebDriver>(driver).withTimeout(3, SECONDS)
            .pollingEvery(100, MILLISECONDS)
            .ignoring(NoSuchElementException.class)
            .until(new Function<WebDriver, Boolean>() {
              public Boolean apply(WebDriver d) {
                WebElement link = d.findElement(By.linkText(linkText));
                return link.isDisplayed();
              }
            });
        } catch(TimeoutException te) {
          assertFalse(String.format("Timeout waiting for link: '%s'", linkText), true);
        }

Thursday, March 19, 2015




 
Selenium webdriver helps in automating web applications by loading the application in browsers. But during the execution it's not possible to minimize/hide the browser even if the user intend to. There are tweaks such as setting the window size like driver.manage().window().setPosition(new Point(-2000, 0));. But a question arises, if browser is invoked in minimized mode, whats the need of invoking it. Why don't we run it in background? Such a question arised in mind too. A good answer for this is PhantomJS. PhantomJS is a headless WebKit scriptable with a JavaScript API. It has fast and native support for various web standards: DOM handling, CSS selector, JSON, Canvas, and SVG.
Like many other packages, PhantomJS supports Selenium webdriver too. You need to download the executable file from PhantomJS webpage, store the .exe file in class resource path. This can be used to load webdriver.

See below code:

public void navigation() {
DesiredCapabilities caps = new DesiredCapabilities();

String phantompath= loadPhantomJS();

caps.setCapability(PhantomJSDriverService.PHANTOMJS_EXECUTABLE_PATH_PROPERTY, phantompath);

try{

driver = new PhantomJSDriver(caps);

}

catch(IllegalStateException ie){

if(driver!=null){

driver.quit();

}

}

driver.manage().window().setSize(new Dimension(1124,1024));
driver.get(obj.getProperty("url"));

    }


private static String loadPhantomJS() {
        String phantomJs = "phantomjs.exe";
        String dir1 = System.getProperty("user.dir");;
        try {
            InputStream in = Exitfunctions.class.getResourceAsStream("/phantom/" + phantomJs);
            File fileOut = new File(dir1 +"/"+ phantomJs);
            OutputStream out = FileUtils.openOutputStream(fileOut);
            IOUtils.copy(in, out);
            in.close();
            out.close();
            return fileOut.getAbsolutePath();
        } catch (Exception e) {
            return "";
        }
    } 



PhantomJS need to quit once the execution is done or any exception occurs. Unless, PhantomJS service will be running in background which may cause exception while next execution of your program. You may use driver.quit(); itself.

Link to download PhantomJS: http://phantomjs.org/

>

Selenium useful links

Powered by Blogger.

Featured Post

Benefits of having a user Interface for a Selenium Automation Suite/Regression Suite

Once you are able to work independently on Selenium scripting, another important task is how to ease your automation test execution. There a...

Video

Popular Posts

Our Facebook Page