Apache ANT 与 Selenium:完整教程

什么是 Apache Ant?

在创建完整的软件产品时,需要注意不同的第三方 API、它们的类路径、清理以前的可执行二进制文件、编译源代码、执行源代码、创建报告和部署代码库等。如果这些任务都是手动逐一完成的,那么将会花费大量的时间,而且这个过程很容易出错。

这就是 Ant 这样的构建工具的重要性。它按照 Ant 配置文件(通常是 build.xml)中提到的顺序存储、执行和自动化所有流程。

阿帕奇蚂蚁

Ant build 的好处

  1. Ant 创建应用程序生命周期,即清理、编译、设置依赖、执行、报告等。
  2. 第三方 API 依赖项可以通过 Ant 设置,即其他 Jar 文件的类路径由 Ant 构建文件设置。
  3. 创建完整的应用程序以实现端到端交付和部署。
  4. 它是一个简单的构建工具,其中所有配置都可以使用 XML 文件完成,并且可以从命令行执行。
  5. 由于配置与实际应用程序逻辑是分开的,因此它使您的代码干净。

如何安装 Ant

安装 Ant 的步骤 Windows 如下

步骤1) 在MyCAD中点击 软件更新 https://ant.apache.org/bindownload.cgi 或者从以下位置下载 .zip 文件 Apache-ant-1.9.4-bin.zip

安装 Ant

步骤2) 解压文件夹并转到解压文件夹的根目录并复制路径

安装 Ant

步骤3) 转到“开始”->“计算机”->右键单击此处并选择“属性”,然后单击“高级系统设置”

安装 Ant

步骤4) 打开一个新窗口。单击“环境变量…”按钮。

安装 Ant

步骤5) 单击“新建...”按钮,将变量名设置为“ANT_HOME”,将变量值设置为解压文件夹的根路径,然后单击“确定”。

安装 Ant

步骤6) 现在从列表中选择“路径”变量并单击“编辑”并附加;%ANT_HOME%\ bin。

安装 Ant

重新启动系统一次,现在您就可以使用 Ant 构建工具了。

步骤7) 要使用命令行检查 Ant 的版本:

Ant –版本

安装 Ant

理解Build.xml

Build.xml 是 Ant 构建工具最重要的组件。对于 Java 项目,所有清理、设置、编译和部署相关的任务都以 XML 格式在此文件中提及。当我们使用命令行或任何 IDE 插件执行此 XML 文件时,写入此文件的所有指令将按顺序执行。

让我们了解示例 build.XML 中的代码

  • Project 标签用于提及项目名称和 basedir 属性。basedir 是应用程序的根目录
    <project name="YTMonetize" basedir=".">
  • 属性标签用作 build.XML 文件中的变量,以便在后续步骤中使用
<property name="build.dir" value="${basedir}/build"/>
		<property name="external.jars" value=".\resources"/>
	<property name="ytoperation.dir" value="${external.jars}/YTOperation"/>
<property name="src.dir"value="${basedir}/src"/>
  • Target 标签用作按顺序执行的步骤。Name 属性是目标的名称。您可以在一个 build.xml 中拥有多个目标
    <target name="setClassPath">
  • 路径标签用于逻辑地捆绑位于公共位置的所有文件
    <path id="classpath_jars">
  • pathelement 标签将设置所有文件存储的公共位置的根路径
    <pathelement path="${basedir}/"/>
  • pathconvert 标签用于将 path 标签内所有常用文件的路径转换为系统的 classpath 格式
    <pathconvert pathsep=";" property="test.classpath" refid="classpath_jars"/>
  • fileset 标签用于为我们项目中的不同第三方 jar 设置类路径
    <fileset dir="${ytoperation.dir}" includes="*.jar"/>
  • echo 标签用于在控制台上打印文本
<echo message="deleting existing build directory"/>
  • 删除标签将清除指定文件夹中的数据
<delete dir="${build.dir}"/>
  • mkdir 标签将创建新目录
	<mkdir dir="${build.dir}"/>
  • javac 标签用于编译 java 源代码并将 .class 文件移动到新文件夹
        <javac destdir="${build.dir}" srcdir="${src.dir}">
	<classpath refid="classpath_jars"/>
</javac>
  • jar 标签将从 .class 文件创建 jar 文件
	<jar destfile="${ytoperation.dir}/YTOperation.jar" basedir="${build.dir}">
  • manifest 标签将设置要执行的主类
<manifest>
		<attribute name="Main-Class" value="test.Main"/>
</manifest>
  • ‘depends’ 属性用于使一个目标依赖于另一个目标
<target name="run" depends="compile">
  • java 标签将从编译目标部分创建的 jar 中执行 main 函数
<java jar="${ytoperation.dir}/YTOperation.jar" fork="true"/>

使用运行 Ant Eclipse 插入

要从 eclipse 运行 Ant,请转到 build.xml 文件 -> 右键单击​​文件 -> 以... 身份运行 -> 单击构建文件

使用运行 Ant Eclipse 插件

例如:

我们将采用一个小示例程序来非常清楚地解释 Ant 的功能。我们的项目结构如下 -

使用运行 Ant Eclipse 插件

在这个例子中,我们有 4 个目标

  1. 设置外部 jar 的类路径,
  2. 清理之前编译的代码
  3. 编译现有的 Java 代码
  4. 运行代码

Guru99AntClass.class

package testAnt;		
import java.util.Date;		

public class Guru99AntClass {				
   public static void main(String...s){									       
		System.out.println("HELLO GURU99 ANT PROGRAM");					        
		System.out.println("TODAY's DATE IS->"+ currentDate() );					  
}		    		   
public static String currentDate(){					        
	return new Date().toString();					  
	}		
}

构建.xml

 
<?xml version="1.0" encoding="UTF-8"	standalone="no"?>									
<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->	

<project name="YTMonetize" basedir=".">								
     <!--Property tags will be used as variables in build.xml file to use in further steps-->		

	<property name="build.dir" value="${basedir}/build"/>								
    <property name="external.jars" value=".\resources"/>								
		<property name="ytoperation.dir" value="${external.jars}/YTOperation"/>
<property name="src.dir"value="${basedir}/src"/>
<!--Target tags used as steps that will execute in sequential order. name attribute will be the name  of the target and < a name=OLE_LINK1 >'depends' attribute used to make one target to depend on another target -->		
	       <target name="setClassPath">					
			<path id="classpath_jars">						
				<pathelement	path="${basedir}/"/>					
			</path>				         
<pathconvert	pathsep=";"property="test.classpath" refid="classpath_jars"/>	
</target>				
	<target name="clean">						
		<!--echo tag will use to print text on console-->		
		<echo message="deleting existing build directory"/>						
		<!--delete tag will clean data from given folder-->		
		<delete dir="${build.dir}"/>						
	</target>				
<target name="compile" depends="clean,setClassPath">								
	<echo message="classpath:${test.classpath}"/>					
			<echo message="compiling.........."/>						
	<!--mkdir tag will create new director-->							
	<mkdir dir="${build.dir}"/>						
		<echo message="classpath:${test.classpath}"/>						
		<echo message="compiling.........."/>						
	<!--javac tag used to compile java source code and move .class files to a new folder-->		
	<javac destdir="${build.dir}" srcdir="${src.dir}">								
			<classpath refid="classpath_jars"/>						
	</javac>				
	<!--jar tag will create jar file from .class files-->		
	<jar	destfile="${ytoperation.dir}/YTOperation.jar"basedir="${build.dir}">								
	            <!--manifest tag will set your main class for execution-->		
						<manifest>				
							<attribute name="Main-Class" value="testAnt.Guru99AntClass"/>  
</manifest>		
</jar>				
    </target>				
	<target name="run" depends="compile">								
		<!--java tag will execute main function from the jar created in compile target section-->	
<java jar="${ytoperation.dir}/YTOperation.jar"fork="true"/>			
</target>				
	</project>				

使用运行 Ant Eclipse 插入

如何执行 TestNG 使用 Ant 的代码

执行 TestNG 使用 Ant 的代码

在这里我们将创建一个类 测试 方法并设置类路径 测试 在 build.xml 中。

现在为了执行 testng 方法,我们将创建另一个 testng.xml 文件并从 build.xml 文件中调用此文件。

步骤1) 我们创建一个 “Guru99AntClass.class” 在包装中 测试蚂蚁

Guru99AntClass.class

package testAnt;
import java.util.Date;
import org.testng.annotations.Test;		
public class Guru99AntClass {				
    @Test		  
	public void Guru99AntTestNGMethod(){					     
		System.out.println("HELLO GURU99 ANT PROGRAM");					
		System.out.println("TODAY's DATE IS->"+ currentDate() );					
	}		
	public static String currentDate(){					
		return new Date().toString();					
	}		
}		

步骤2)在Build.xml中创建一个目标来加载该类

<!-- Load testNG and add to the class path of application -->
	<target name="loadTestNG" depends="setClassPath">
<!—using taskdef  tag we can add a task to run on the current project. In below line, we are adding testing task in this project. Using testing task here now we can run testing code using the ant script -->
		<taskdef resource="testngtasks" classpath="${test.classpath}"/>
</target>

步骤3) 创建 testng.xml

测试ng.xml

<?xml version="1.0"encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="YT"thread-count="1">
			<test name="GURU99TestNGAnt">
			<classes>
			   <class name="testAnt.Guru99AntClass">
	</class>
</classes>
</test>
</suite>

步骤4) 创建 Target 在 Build.xml 中运行此 TestNG 码

<target name="runGuru99TestNGAnt" depends="compile">
<!-- testng tag will be used to execute testng code using corresponding testng.xml file. Here classpath attribute is setting classpath for testng's jar to the project-->
	<testng classpath="${test.classpath};${build.dir}">
<!—xmlfileset tag is used here to run testng's code using testing.xml file. Using includes tag we are mentioning path to testing.xml file-->
	 <xmlfileset dir="${basedir}" includes="testng.xml"/>
</testng>				

步骤5) 完整的Build.xml

<?xml version="1.0"encoding="UTF-8"standalone="no"?>
<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->
			<project name="YTMonetize" basedir=".">
		       <!--Property tags will be used as variables in build.xml file to use in further steps-->
			<property name="build.dir"value="${basedir}/build"/>
<!-- put  testng related jar in the resource  folder -->
	      <property name="external.jars" value=".\resource"/>
				<property name="src.dir" value="${basedir}/src"/>
<!--Target tags used as steps that will execute in  sequential order. name attribute will be the name
    of the target and 'depends' attribute used to make one target to depend on another target-->
<!-- Load testNG and add to the class path of application -->
         <target name="loadTestNG"depends="setClassPath">
				<taskdef resource="testngtasks"classpath="${test.classpath}"/>
		</target>
		<target name="setClassPath">
		       <path id="classpath_jars">
					<pathelement path="${basedir}/"/>
					<fileset dir="${external.jars}" includes="*.jar"/>
         </path>
        <pathconvert pathsep=";"property="test.classpath"refid="classpath_jars"/>
	</target>
	<target name="clean">
              <!--echo tag will use to print text on console-->
	               <echo message="deleting existing build directory"/>
               <!--delete tag will clean data from given folder-->
	               <delete				dir="${build.dir}"/>
			</target>
<target name="compile"depends="clean,setClassPath,loadTestNG">
	         <echo message="classpath:${test.classpath}"/>
	               <echo	message="compiling.........."/>
		       <!--mkdir tag will create new director-->
		        <mkdir dir="${build.dir}"/>
					<echo message="classpath:${test.classpath}"/>
			<echo message="compiling.........."/>
	<!--javac tag used to compile java source code and move .class files to a new folder-->
	        <javac destdir="${build.dir}"srcdir="${src.dir}">
	             <classpath refid="classpath_jars"/>
		</javac>
  </target>
<target name="runGuru99TestNGAnt"depends="compile">
		<!-- testng tag will be used to execute testng code using corresponding testng.xml file -->
			<testng classpath="${test.classpath};${build.dir}">
               <xmlfileset dir="${basedir}"includes="testng.xml"/>
	</testng>
</target>
</project>

步骤6) 输出

执行 TestNG 使用 Ant 的代码

下载上述文件

蚂蚁 Selenium 网络驱动程序

到目前为止,我们已经了解到,使用 ANT,我们可以将所有第三方 jar 放在系统中的特定位置,并为我们的项目设置它们的路径。使用这种方法,我们可以在一个地方设置项目的所有依赖项,并使编译、执行和部署更加可靠。

类似地,对于我们使用 selenium 的测试项目,我们可以在 build.xml 中轻松提及 selenium 依赖项,并且我们不需要在应用程序中手动添加它的类路径。

所以现在您可以忽略下面提到的为项目设置类路径的传统方式。

蚂蚁 Selenium 网络驱动程序

示例:

我们将修改前面的例子

步骤1) 将属性selenium.jars设置为资源文件夹中的selenium相关jar

		<property name="selenium.jars" value=".\selenium"/>

步骤2) 在目标 setClassPath 中,添加 selenium 文件

<target name="setClassPath">
	        <path id="classpath_jars">
				<pathelement path="${basedir}/"/>	
				<fileset dir="${external.jars}" includes="*.jar"/>
	            <!-- selenium jar added here -->
  		            <fileset dir="${selenium.jars}" includes="*.jar"/>
         </path>		

步骤3) 完成Build.xml:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<!--Project tag used to mention the project name, and basedir attribute will be the root directory of the application-->
			<project name="YTMonetize" basedir=".">
                  <!--Property tags will be used as variables in build.xml file to use in further steps-->
				<property name="build.dir" value="${basedir}/build"/>
      <!-- put  testng related jar in the resource  folder -->
	       <property name="external.jars" value=".\resource"/>
<!-- put  selenium related jar in resource  folder -->
     <property name="selenium.jars" value=".\selenium"/>
			<property name="src.dir" value="${basedir}/src"/>
				<!--Target tags used as steps that will execute in  sequential order. name attribute will be the name 
of the target and 'depends' attribute used to make one target to depend on another target-->
      <!-- Load testNG and add to the class path of application -->
       <target name="loadTestNG" depends="setClassPath">
				<taskdef resource="testngtasks" classpath="${test.classpath}"/>
		</target>
<target name="setClassPath">
	        <path id="classpath_jars">
				<pathelement path="${basedir}/"/>
					<fileset dir="${external.jars}" includes="*.jar"/>
			<!-- selenium jar added here -->
	            <fileset dir="${selenium.jars}"includes="*.jar"/>
        </path>
   <pathconvert pathsep=";" property="test.classpath" refid="classpath_jars"/>
</target>
<target name="clean">
<!--echo tag will use to print text on console-->
               <echo message="deleting existing build directory"/>
	                <!--delete tag will clean data from given folder-->
		               <delete dir="${build.dir}"/>
				</target>
<target name="compile" depends="clean,setClassPath,loadTestNG">
         <echo message="classpath:${test.classpath}"/>
                <echo message="compiling.........."/>
        <!--mkdir tag will create new director-->
	        <mkdir dir="${build.dir}"/>
          			<echo message="classpath:${test.classpath}"/>
			<echo message="compiling.........."/>
	<!--javac tag used to compile java source code and move .class files to new folder-->
     <javac destdir="${build.dir}"srcdir="${src.dir}">
             <classpath refid="classpath_jars"/>
	</javac>
</target>
<target name="runGuru99TestNGAnt" depends="compile">
		<!-- testng tag will be used to execute testng code using corresponding testng.xml file -->
			<testng classpath="${test.classpath};${build.dir}">
               <xmlfileset dir="${basedir}" includes="testng.xml"/>
		</testng>
	</target>
</project>

步骤4) 现在用新代码更改先前创建的类 Guru99AntClass.java。

在此示例中,我们使用的步骤 Selenium 是:

  1. 在MyCAD中点击 软件更新 http://demo.guru99.com/test/guru99home/
  2. 逐一阅读所有课程链接
  3. 在控制台上打印所有课程超链接。

Guru99AntClass.java:

package testAnt;		
import java.util.List;		
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;	
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class Guru99AntClass {

	@Test		
		public void Guru99AntTestNGMethod(){
	      WebDriver driver = new FirefoxDriver();	
		  driver.get("http://demo.guru99.com/test/guru99home/");
		  List<WebElement> listAllCourseLinks = driver.findElements(By.xpath("//div[@class='canvas-middle']//a"));							        
          for(WebElement webElement : listAllCourseLinks) {
			System.out.println(webElement.getAttribute("href"));
      	  }
		}
}		

步骤5) 执行成功后输出如下:

蚂蚁 Selenium 网络驱动程序

下载上述示例文件

总结

Ant 是一个构建工具 Java.

Ant用于代码的编译、部署、执行过程。

Ant 可以从以下网址下载 阿帕奇 网站。

Build.xml 文件用于使用 Ant 配置执行目标。

Ant 可以从命令行或合适的 IDE 插件(如 eclipse)运行。