Apache ANT 教程

⚡ 智能摘要

Apache Ant 是一个开源的, Java基于构建工具,可通过单个 build.xml 文件自动完成编译、测试、打包和部署。与 Selenium 和 TestNG它使测试执行可重复、有条理,并且易于在任何地方运行。

  • 🐜 核心角色: Ant 根据 XML 配置文件按顺序存储和运行构建步骤。
  • ⚙️ 构建生命周期: 一个文件即可处理清理、编译、设置类路径、执行和报告等操作。
  • 📦 build.xml 结构: 项目、目标、任务和属性标签定义了每个构建步骤。
  • 🔧 安装方式: 设置 ANT_HOME 变量并将 %ANT_HOME%\bin 添加到系统路径。
  • 🧪 Selenium 和 TestNG: Ant 会调用 testng.xml,以便在构建过程中运行测试套件。
  • 🚀 依赖控制: 第三方 JAR 路径集中化,提高了可靠性和部署效率。

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 的代码

下载上述文件

由 Ant 管理构建和 TestNG 接线完成后,下一步是将Ant直接连接到 Selenium WebDriver。

蚂蚁 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中点击 软件更新 https://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("https://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 是一种过程式构建工具,需要手动编写每个步骤的脚本;而 Maven 是声明式的,它通过中央仓库自动管理依赖项。Ant 提供更多控制权,Maven 则提供约定。

是的。许多遗留问题 Java 和 Selenium 项目仍然依赖 Ant 进行构建和持续集成。较新的项目通常选择 Maven 或 Gradle但是 Ant 在细粒度构建控制方面仍然很有用。

Apache Ant 1.10.x 是目前仍在积极维护的版本,并且需要 Java 8 或更高版本。较旧的 1.9.x 系列支持旧版本。 Java请务必从官方网站 ant.apache.org 下载二进制文件。

是的。像 ChatGPT 或 Copilot 这样的 AI 助手会生成 build.xml 目标,建议任务定义,并解释错误。 Rev请仔细查看生成的 XML,因为路径和依赖项版本仍需验证。

人工智能驱动的工具生成 TestNG 它们可以优化测试套件,优化测试顺序,并标记通过 Ant 目标触发的不稳定测试。它们通过建议定位器修复方案和自动分析构建报告来减少维护工作。

不。Ant 可以编译并直接运行。 Java or JUnit 测试也包括在内。 TestNG 只是通过 testng.xml 添加了灵活的套件配置,Ant 在构建期间使用 testng 任务调用它。

ANT_HOME 告诉操作系统 Ant 的安装位置,以便 ant 命令可以从任何目录运行。安装过程中,您需要将 %ANT_HOME%\bin 添加到系统路径中。 Windows.

Gradle 对于新项目,Maven 通常是首选,因为它结合了 Ant 的灵活性、Maven 的依赖管理功能以及更快的增量构建速度。选择 Ant 的主要目的是为了维护现有的构建脚本。

总结一下这篇文章: