Sunday, July 17, 2011

Execute a java class using Ant

Sample Ant Script

<project name="selenium-demo" default="compile" basedir=".">

    <property name="build.dir" value="build" />
    <property name="src.dir" value="src"/>
    <property name="lib.dir" value="lib"/>
    <property name="reports.dir" value="report"/>
    <property name="xml" value="Sample.xml"/>
    <property name="main-class"  value="mytests.Sample"/>
 
    <path id="classpath">
        <pathelement location="${build.dir}/classes"/>
        <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

    <target name="compile">
        <delete dir="${build.dir}"/>
        <mkdir dir="${build.dir}/classes"/>
        <javac srcdir="${src.dir}" destdir="${build.dir}/classes"  executable="javac">
            <classpath refid="classpath"/>
        </javac>
    </target>

    <target name="run_tests" depends="compile">
        <java classname="${main-class}">
             <classpath refid="classpath"/>
        </java>
    </target>

</project>

Save the above file as ant.xml.

Sample Java File


package mytests;

import java.io.IOException;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;


public class Sample{
 
    public static void main(String str[]){
         WebDriver driver = new FirefoxDriver();
         driver.get("http://www.addthis.com");
         try {
            Thread.sleep(5);
        } catch (InterruptedException e) {
        }
        driver.close();
    }

}

Save the java file as Sample.java and put it into a folder named "src" . Create a new folder and name it "lib" and paste the jar files to be used in the project. For above project only "selenium-server-standalone" will be enough. From the CMD go to the project location and excute the command ant run_tests. Now a new folder called build will be created and it will have all compiled classes.

No comments:

Post a Comment