Monday, 18 February 2013

Simple WebDriver Framework Using Java


This post contains the information about setting up simple WebDriver framework.  The framework is created to keep the design as much as simple, easy to understand and extendible. I have used TestLink webapp to use as an example (For TestLink configuration, visit the page – http://testlinkconfiguration.blogspot.in/).

Technologies Used –

  • Selenium 3.0 (WebDriver) – For UI Automation.
  • JUnit – For Unit Test.
  • Ant – For Report Generation

Pre-requisites - 

Java should be available –
Java JDK (greater than 1.7) should be installed on the system. 

Required Jar Files –
                selenium-java-3.12.0.jar
    selenium-java-standalone-3.12.0.jar
    junit-4.12.jar
Required Browser related files –
                Geckodriver.exe (https://github.com/mozilla/geckodriver/releases)
                Chromedriver.exe (http://code.google.com/p/chromedriver/downloads/list)
                IEDriverServer.exe (http://code.google.com/p/selenium/downloads/list)

Framework Highlights –

  • Used basic Java features, JUnit and Ant for creating and executing scripts.
  • Methods common across the scripts has defined in the “CommonFuntions.java” file. So all the scripts can use the methods from this file.
  • Web page elements, Browsers name and values are contained in properties file called “TestLink.properties” file. Scripts only contain the variable name from this properties file.  This reduces the dependency of hardcore values from the scripts.
  • Created source folders for every TestLink modules (ex – TestProject, TestSpecifications etc) so we have scripts based on the features and can easily mapped the test cases.
  • Every source folder/feature has at least one main file (ex - TestProject_Main.java) which contains all the test cases respectively. Because of this we can also execute the scripts based on the features.
  • All the jar files and required browser related files are stored under “lib” folder.

 Framework Design -

  • Download Eclipse installer (eclipse-inst-win64) www.eclipse.org
  • Double click on the installer and install in any directory (In my case – D:\eclipse for Windows or /Users/<username>/eclipse on Mac.
  • Launch Eclipse. Browse the path of your workspace. Click on ‘OK’ button.


  • Select File->New->Java Project from Eclipse main menu.


  • Enter the Project name (ex- TestLink_Automation_V0) on below screen. Click on Finish button.



  • Now the project name (ex - TestLink_Automation_V0) appears in Eclipse. See below screen – 


  • Right click on project name (ex - TestLink_Automation_V0) and select New->Folder menu.
  • Enter the Folder name “lib” and click on Finish button. See the below screen -



  • Now Package Explorer looks like this –
  • Copy all the below jar and browsers related files into this “lib” folder –

a.       selenium-java-3.12.0.jar
b.      selenium-java-standalone-3.12.0.jar
c.       Junit-4.12.jar
d.      geckodriver
e.      chromedriver
f.        IEDriverServer.exe

  • Select Project name from Package Explorer. Click on Project->Properties from Eclipse main menu. Shows below screen.
  • Select “Java Build Path” from left side. Click on Libraries tab. Shows above screen.
  • Click on “Add JARs..” button.  Expand the Project name and then lib folder.

  • Select all the Jar files and click on Ok button. Shows below screen –
  • Click Ok button on Java Build Path screen.
  • Right click on project name and select New->Source Folder
  • Enter the Source Folder name.
  • Click on Finish button. Now Package Explorer looks like below –
  • Repeat the steps 16-18 for another source folder (ex – User Management). Note – For any other source folder, follow the same steps.
  • Create common function java file. This file contains the methods which have been used across all the scripts. For creating this, right click on the project and select New->Class.
  • Enter the Class name and click on Finish button.

  • Create Properties file. This file contains all the application controls, hardcore values, setting browser name etc which have been used across the scripts. For creating this, right click on the project and select New->File menu.
  •  Enter the File name (ex - TestLink.properties) and click on Finish button.
  • Start creating test scripts. For creating this, right click on source folder (ex - TestProject) and select New->Class. Enter the Class name and click on finish button.
  • Create “build.xml” file for running script using Ant and get the HTML report. For creating this file, right click on the project and select New->File menu. Enter the file name “build.xml” and click on Finish button.
  • Now project framework looks like below -


Creating Properties (TestLink.properties) file –

Web page elements, Browsers name and values are contained in properties file called “TestLink.properties” file. Scripts only contain the variable name from this properties file.  This reduces the dependency of hardcore values from the scripts. Normally we create the property variable and assign into the respective variable. Ex –
           


In the script, you can simply use the variable. Later if there is any change in value, we only need to update the properties file not all the script files.

Loading Properties file –
Java provides the utility to load the properties file and get the individual property from this. See the below code to load the properties file –

                Properties prop = new Properties();
                try {
               //load a properties file
                                prop.load(new FileInputStream("TestLink.properties"));
             
                } catch (IOException ex) {
                                ex.printStackTrace();
                 }

Details about common functions –

Methods common across the scripts has defined in the “CommonFuntions.java” file. So all the scripts can use the methods from this file. See below the current common methods are –

           
Details about Test Script design –
 We have used JUnit for creating and executing test cases. The test scripts has divided into three sections –
1)      setup
2)      Test Script
3)      Teardown

  • SetUp method – This method contains the initialization of variables, properties and browser driver and application URL. See the below code block as an example –
@BeforeClass
public static void setUp() throws IOException
{
                try {
            //load a properties file
                prop.load(new FileInputStream("TestLink.properties"));
                } catch (IOException ex)
                {
                                ex.printStackTrace();
                }
                driver=CommonFunctions.getWebDriver(prop);
                driver.manage().deleteAllCookies();
                wdw = new WebDriverWait(driver, 30);
                driver.get("http://localhost/testlink/login.php");
                driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS);
}
  • Test Script – The test script is divided into two parts – First, call the test script from main file and second, actual implementation of test case is in separate file. See the below example code –
@Test
 public void test1_VerifyLoginNameHeader()
 {
System.out.println("@Test Case-1:Verify LoginName in header on the home page");
TestProject_TCases.TestCase1(driver, wdw, prop);
}
  • TearDown – This method contains the application logout, closing the app and browser. See the below code example –
@AfterClass
public static void tearDown()
{
                driver.switchTo().defaultContent();
                driver.switchTo().frame("titlebar");
                driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();   
                driver.quit();
                CommonFunctions.wait(100);
}


Script Executing mode – Using this framework, we can execute the script in two modes –
1)      Using JUnit
2)      Using Ant.

Example Scripts
  • Put the Files TestProject_Main.java and TestProject_TCases.java under TestProject source folder.
  • Put the TestLink.properties and CommonFunctions.java files directly under “TestLink_Automation_V0” project
TestProject_Main.java
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;
public class TestProject_Main
{
                public static WebDriver driver;
                public static WebElement element;
                public static WebDriverWait wdw;
                public static Properties prop = new Properties();
               
                @BeforeClass
                public static void setUp() throws IOException
                {
                                try {
            //load a properties file
                                                prop.load(new FileInputStream("TestLink.properties"));
                                                } catch (IOException ex)
                                                {
                                                                ex.printStackTrace();
                                                }
                                driver=CommonFunctions.getWebDriver(prop);
                                driver.manage().deleteAllCookies();
                                wdw = new WebDriverWait(driver, 30);
                                driver.get("http://localhost/testlink/login.php");
                                driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
                                driver.findElement(By.xpath(prop.getProperty("TXT_UNAME"))).sendKeys("admin");
                                driver.findElement(By.xpath(prop.getProperty("TXT_PWD"))).sendKeys("admin");
                                driver.findElement(By.xpath(prop.getProperty("BTN_LOGIN"))).click();
                                CommonFunctions.wait(100);
                }
                @Test
    public void test1_VerifyTestProjectMangtLink()
    {
                                System.out.println("@Test Case-1:Verify Test Project Management on the home page");
                                TestProject_TCases.TestCase1(driver, wdw, prop);
                }
                @Test
    public void test2_VerifyAssignUserRolesLink()
    {
                                System.out.println("@Test Case-2:Verify Assign User Role on the home page");
                                TestProject_TCases.TestCase2(driver, wdw, prop);
                }
                               
                @AfterClass
                public static void tearDown()
                {
                                driver.switchTo().defaultContent();
                                driver.switchTo().frame("titlebar");
                                driver.findElement(By.xpath("//a[contains(text(),'Logout')]")).click();
                                driver.quit();
                                CommonFunctions.wait(100);
                }

}

TestProject_TCases.java
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestProject_TCases
{
                //Test1
                                public static void TestCase1(WebDriver wd,WebDriverWait wd_wait,Properties prop)
                                {
                                                wd.switchTo().frame("mainframe");
                                                WebElement element=wd.findElement(By.xpath(prop.getProperty("LNK_TESTPRJMANM")));
                                                if(element.isDisplayed())
                                                {
                                                                element.click();
                                                                System.out.println("Click on the Test Project Management link");
                                                }
                                                CommonFunctions.wait(100);
                                                wd.switchTo().defaultContent();
                                                wd.switchTo().frame("titlebar");
                                                wd.findElement(By.xpath(prop.getProperty("TAB_PROJECT"))).click();
                                }
                                //Test2
                                public static void TestCase2(WebDriver wd,WebDriverWait wd_wait,Properties prop)
                                {
                                                wd.switchTo().frame("mainframe");
                                                WebElement element=wd.findElement(By.xpath(prop.getProperty("LNK_USERROLE")));
                                                if(element.isDisplayed())
                                                {
                                                                element.click();
                                                                System.out.println("Click on the Assign User Roles link");
                                                }
                                                CommonFunctions.wait(100);
                                                wd.switchTo().defaultContent();
                                                wd.switchTo().frame("titlebar");
                                                wd.findElement(By.xpath(prop.getProperty("TAB_PROJECT"))).click();
                                }

}

TestLink.properties
#Please use the following browsers - FIREFOX, IE, CHROME, HTMLUNIT, ANDROID, SAFARI
BROWSER=FIREFOX

#TestLink Login
TXT_UNAME=//input[@name='tl_login']
TXT_PWD=//input[@name='tl_password']
BTN_LOGIN=//input[@name='login_submit']

#Home Screen - Tabs
TAB_PROJECT=//a[contains(text(),'Project')]

#Home Screen - Test Project
LNK_TESTPRJMANM=//a[contains(text(),'Test Project Management')]
              LNK_USERROLE=//a[contains(text(),'Assign User Roles')]

CommonFunctions.java
import java.io.File;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.android.AndroidDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.safari.SafariDriver;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.Wait;
import com.google.common.base.Function;

public class CommonFunctions
{
                public static void wait(int n)
                {
                                long t0,t1;
                                t0=System.currentTimeMillis();
                                do{
                                                t1=System.currentTimeMillis();
                                }
                                while(t1-t0<n);
                }
                public static WebDriver getWebDriver(Properties prop) throws IOException
                {
                                WebDriver wd;
                                File directory = new File (".");
                                String browser_name=prop.getProperty("BROWSER");
                                    switch (BrowserType.valueOf(browser_name))
                                    {
                                        case FIREFOX:
                                            wd=new FirefoxDriver();
                                            wd.manage().window().maximize();
                                            return wd;
                                        case IE:
                                                String iepath=directory.getCanonicalPath() + "/lib/" + "IEDriverServer.exe";
                                                //System.out.println(iepath);
                                                System.setProperty("webdriver.ie.driver",iepath);
                                                wd = new InternetExplorerDriver();
                                                wd.manage().window().maximize();
                                            return wd;
                                        case CHROME:
                                                String chromepath=directory.getCanonicalPath() + "/lib/" + "chromedriver.exe";
                                                //System.out.println(driverpath);
                                                System.setProperty("webdriver.chrome.driver", chromepath);
                                                wd = new ChromeDriver();
                                                CommonFunctions.wait(5000);
                                                wd.manage().window().maximize();
                                            return wd;
                                        case HTMLUNIT:
                                                wd = new HtmlUnitDriver();
                                            return wd;
                                        case ANDROID:
                                                wd = new AndroidDriver();
                                            return wd;
                                        case SAFARI:
                                                wd = new SafariDriver();
                                                wd.manage().window().maximize();
                                            return wd;
                                        default:
                                            throw new RuntimeException("Browser type unsupported");
                                    }
                }
                                 
                public static enum BrowserType
                {
                                    FIREFOX, IE, CHROME, HTMLUNIT, ANDROID, SAFARI
                }
                public static WebElement fluentWait(WebDriver driver,final By locator){
        Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
                .withTimeout(30, TimeUnit.SECONDS)
                .pollingEvery(5, TimeUnit.SECONDS)
                .ignoring(NoSuchElementException.class);

        WebElement foo = wait.until(new Function<WebDriver, WebElement>()
        {
            public WebElement apply(WebDriver driver)
            {
                return driver.findElement(locator);
            }
         }
                                );
        return  foo;
        };
                public static boolean verifyTextPresent(WebDriver wd,String text)
                {
                                return wd.getPageSource().contains(text);
                }
                public static boolean WaitTextPresent(WebDriver wd,String text)
                {
                                int k=1;
                                boolean val1=false;
                                while(k !=0)
                                {
                                                boolean val=wd.getPageSource().contains(text);
                                                if(val==true)
                                                {
                                                                k=0;
                                                                val1=true;
                                                }
                                                else
                                                {
                                                                wait(500);
                                                                k=1;
                                                }
                                }
                                return val1;
                }
}


Build.xml
<?xml version="1.0" encoding="UTF-8"?>
<project name="TestLink" default="exec" basedir=".">

                <property name="src" value="./src" /><!-- Change it to your source folder -->
                <property name="project" value="./TestProject" />
                <property name="lib" value="./lib" /><!-- Change it to your lib folder -->
                <property name="bin" value="./bin" /><!-- Change it to your bin folder -->
                <property name="report" value="./report" /><!-- Change it to your report folder -->
                <path id="test.classpath"><!-- Creating a classpath for use while compiling -->
                                <pathelement location="${bin}" />
                                <fileset dir="${lib}">
                                                <include name="**/*.jar" />
                                </fileset>
                </path>

                <target name="init"><!-- Initialization target which deletes and recreates the binary folder.-->
                                <delete dir="${bin}" />
                                <mkdir dir="${bin}" />
                </target>
<!--Section1-->
                <target name="compile" depends="init"><!-- Target for compiling the source folder  -->
                                <javac source="1.7" srcdir="${src};${project}" fork="true" destdir="${bin}" >
                                                <classpath>
                                                                <pathelement path="${bin}">
                                                                </pathelement>
                                                                <fileset dir="${lib}">
                                                                                <include name="**/*.jar" />
                                                                </fileset>
                                                </classpath>
                                </javac>
                </target>

                <target name="exec" depends="compile">
                                <delete dir="${report}" />
                                <mkdir dir="${report}" />
                                                <mkdir dir="${report}/xml" />
                                <junit printsummary="yes" haltonfailure="no">
                                                <classpath>
                                                                <pathelement location="${bin}" />
                                                                <fileset dir="${lib}">
                                                                                <include name="**/*.jar" />
                                                                </fileset>
                                                </classpath>

                                                <formatter type="plain"/>
                                                                                                <formatter type="xml"/>
                                                                      <batchtest fork="yes" todir="${report}/xml">
                                                                        <fileset dir="${project}">
                                                                                <include name="**/*.java"/>
                                                                                <exclude name="**/TestProject_TCases.java"/>
                                                                        </fileset>
                                                                                                                                               
                                                                     </batchtest>
                                               
                                </junit>
                                <junitreport todir="${report}"><!-- This section generated the Junit report in html to "html" folder from the xml file. -->
                                                <fileset dir="${report}/xml">
                                                                <include name="TEST*.xml" />
                                                </fileset>
                                                <report format="frames" todir="${report}/html" />
                                </junitreport>
                </target>
</project>

No comments:

Post a Comment