Sunday, October 16, 2016

Once you are able to work independently on Selenium scripting, another important task is how to ease your automation test execution. There are various methods for Selenium  execution. In continuous integration, depending on Jenkins integration is a necessity. Automation execution using Jenkins will enable you to perform mass execution, scheduling etc.

                           I have derived another method which will ease your execution to a certain extent. It is by creating a user interface for your automation framework. It will also give a grant appeal to the framework you have created.

For this you need not have much of UI designing skills. With the help of WindowBuilder addon in Eclipse you can create a UI. I have explained this in a previous post. Please follow the link: Click here

How to export the Project to a runnable JAR

1) You can export the whole project to a runnable JAR with UI class as the main class


a) Export the Project




b) Select Runnable JAR under Java



c)

Against the Launch Configuration dropdown-> Select the UI class as main class 
Enter the destination with .jar extension against Export destination





















d)  Click Finish. Your runnable JAR will be created in the given folder


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

1) You may select dynamic values like Dev/QA Url from the UI and execute, browser: Chrome, Firefox etc
2) This jar can be executed in any system provided JRE is installed. So developers can do unit testing(Eclipse not required)







Saturday, April 2, 2016

I have researched lot, how to execute the TestNG xml from a Java class because I wanted to make my whole project in to a Runnable JAR file and execute it anywhere outside eclipse. This was already in the TestNG docs, but I couldn't understand this first time.

Advantages of this method:


  • You can execute your tests outside eclipse, any machine provided JRE is installed on the machine. You don't need to place the libraries too, The JAR will have all these.
  • Without a Selenium grid, this enables you to  run the tests on any previous versions of browsers running on another machine.
  • This can be executed by anyone without any knowledge of Eclipse, scripting etc.


How to do this:

Assuming you are running your test cases by executing testNG.xml as TestNG.

Steps:

Create a Java class with main method with below code.


public class MainTest {
    public static void main(String[] args){
    List<String> file = new ArrayList<String>();
    file.add("D:/Selenium_workspace/Framework/src/Framework.xml");
    TestNG testNG = new TestNG();
    testNG.setTestSuites(file);
    testNG.run();}
}



Now Export your whole project to runnable JAR. Double click the JAR, will execute the xml as testNG. You may create a user interface to select XML so that it adds flexibility to select which test you need to run.


In this post I will give you a code how to automate selection of date from a date widget neither has the date input and also direct navigation to the months/years. This widget only has the 'Prev', 'Next' buttons to navigate to next months/previous months.













Please find the code below:


public class DateWidgetSample {
public static void main(String args[]){
 String date1="12/04/2016";
 String date2="12/12/2015";

 SimpleDateFormat fmt= new SimpleDateFormat("dd/MM/yyyy");
 Date datevar1 = null;
 Date datevar2 = null;
 try {
  datevar1 = fmt.parse(date1);
  datevar2 = fmt.parse(date2);
 } catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 Calendar cal1 = Calendar.getInstance();
 Calendar cal2 = Calendar.getInstance();
 cal1.setTime(datevar1);
 cal2.setTime(datevar2);

 cal1.set(Calendar.DAY_OF_MONTH, 1);
 cal2.set(Calendar.DAY_OF_MONTH, 1);

 int diffYear = cal2.get(Calendar.YEAR) - cal1.get(Calendar.YEAR);
 int diffMonth = diffYear * 12 + cal2.get(Calendar.MONTH) - cal1.get(Calendar.MONTH);

 System.out.println(diffMonth);
}
}



Result output is difference of months.


Next you have to do is have a for loop to click the previous/next button based on the number of months obtained in the output. If the number is a positive value, ask to click the next button. If it's a negative value, click the Previous button. That's all. Check code below.

if(diffMonth>0){
for(int i=0; i<diffMonth; i++){
driver.findElement(By.id("nextbtn").click();
}
}

if(diffMonth<0){
for(int j=0; j<diffMonth; j++){
driver.findElement(By.id("previousbtn").click();
}
}





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>


>

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