Apache ANT с Selenium: Полное руководство
Что такое Apache Ant?
При создании полноценного программного продукта необходимо позаботиться о различных сторонних API, их пути к классам, очистке предыдущих исполняемых двоичных файлов, компиляции нашего исходного кода, выполнении исходного кода, создании отчетов и базы кода развертывания и т. д. Если эти задачи Если выполнять один за другим вручную, это займет огромное время, и этот процесс будет подвержен ошибкам.
Здесь проявляется важность такого инструмента сборки, как Ant. Он хранит, выполняет и автоматизирует все процессы в последовательном порядке, указанном в файле конфигурации Ant (обычно build.xml).
Преимущества сборки Ant
- Ant создает жизненный цикл приложения, т. е. очистку, компиляцию, установку зависимостей, выполнение, отчет и т. д.
- Зависимость стороннего API может быть установлена Ant, т.е. путь к классу другого файла Jar устанавливается файлом сборки Ant.
- Полное приложение создается для сквозной доставки и развертывания.
- Это простой инструмент сборки, в котором все конфигурации можно выполнить с использованием файла XML и запустить из командной строки.
- Это делает ваш код чистым, поскольку конфигурация отделена от реальной логики приложения.
Как установить Ант
Шаги по установке Ant в Windows как следует
Шаг 1) Перейдите на https://ant.apache.org/bindownload.cgi Или загрузите ZIP-файл с сайта apache-ant-1.9.4-bin.zip
Шаг 2) Разархивируйте папку, перейдите и скопируйте путь к корню разархивированной папки.
Шаг 3) Перейдите в «Пуск» -> «Компьютер» -> щелкните здесь правой кнопкой мыши и выберите «Свойства», затем нажмите «Дополнительные параметры системы».
Шаг 4) Откроется новое окно. Нажмите кнопку «Переменная среды…».
Шаг 5) Нажмите кнопку «Создать…», установите имя переменной «ANT_HOME» и значение переменной в качестве корневого пути к разархивированной папке и нажмите «ОК».
Шаг 6) теперь выберите переменную «Путь» из списка, нажмите «Изменить» и добавьте; %ANT_HOME%\bin.
Перезапустите систему один раз, и теперь вы готовы использовать инструмент сборки Ant.
Шаг 7) Чтобы проверить версию вашего Ant с помощью командной строки:
Ant-версия
Понимание Build.xml
Build.xml — наиболее важный компонент инструмента сборки Ant. Для Java проекта, все задачи, связанные с очисткой, настройкой, компиляцией и развертыванием, упоминаются в этом файле в формате XML. Когда мы выполняем этот XML-файл с помощью командной строки или любого плагина IDE, все инструкции, записанные в этот файл, будут выполняться последовательно.
Давайте разберемся с кодом примера build.XML.
-
Тег проекта используется для указания имени проекта и атрибута 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, используемый для преобразования путей всех общих файлов внутри тега пути в системный формат пути к классам.
<pathconvert pathsep=";" property="test.classpath" refid="classpath_jars"/>
- Тег набора файлов, используемый для установки пути к классам для различных сторонних jar-файлов в нашем проекте
<fileset dir="${ytoperation.dir}" includes="*.jar"/>
- Эхо-тег используется для печати текста на консоли.
<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 создаст файл jar из файлов .class
<jar destfile="${ytoperation.dir}/YTOperation.jar" basedir="${build.dir}">
- тег манифеста установит ваш основной класс для выполнения
<manifest> <attribute name="Main-Class" value="test.Main"/> </manifest>
- Атрибут «зависит», используемый для того, чтобы одна цель зависела от другой цели
<target name="run" depends="compile">
- Тег Java выполнит основную функцию из jar, созданного в разделе цели компиляции.
<java jar="${ytoperation.dir}/YTOperation.jar" fork="true"/>
Запустите Ant, используя Eclipse плагин
Чтобы запустить Ant из eclipse, перейдите в файл build.xml -> щелкните файл правой кнопкой мыши -> Запустить как... -> нажмите «Создать файл».
Пример
Мы возьмем небольшой пример программы, который очень четко объяснит функциональность Ant. Структура нашего проекта будет выглядеть так:
В этом примере у нас есть 4 цели
- Установите путь к классам для внешних jar-файлов,
- Очистить ранее скомпилированный код
- Скомпилируйте существующий Java-код
- Запустите код
Guru99AntClass.класс
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>
Как выполнить TestNG код с использованием Ant
Здесь мы создадим класс с TestNG методы и установите путь к классу для Тестирование в build.xml.
Теперь для выполнения метода testng мы создадим еще один файл testng.xml и вызовем этот файл из файла build.xml.
Шаг 1) Мы создаем «Guru99AntClass.class» в пакете testAnt
Guru99AntClass.класс
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
testng.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) Результат
Муравей с Selenium Вебдрайвер
На данный момент мы узнали, что с помощью ANT мы можем поместить все сторонние jar-файлы в определенное место в системе и указать их путь для нашего проекта. Используя этот метод, мы устанавливаем все зависимости нашего проекта в одном месте и делаем его более надежным для компиляции, выполнения и развертывания.
Аналогично, для наших проектов тестирования, использующих селен, мы можем легко упомянуть зависимость селена в build.xml, и нам не нужно вручную добавлять путь к классу в нашем приложении.
Итак, теперь вы можете игнорировать упомянутый ниже традиционный способ установки путей к классам для проекта.
Пример:
Мы собираемся изменить предыдущий пример
Шаг 1) Установите для свойства selenium.jars значение jar, связанного с селеном, в папке ресурсов.
<property name="selenium.jars" value=".\selenium"/>
Шаг 2) В целевой setClassPath добавьте файлы селена.
<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 составляют:
- Перейдите на
http://demo.guru99.com/test/guru99home/
- Прочтите все ссылки на курсы по одному.
- Распечатайте гиперссылки на все курсы на консоли.
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) После успешного выполнения вывод будет выглядеть так:
Загрузите приведенный выше файл примера
Итого
Ant — это инструмент для сборки Java.
Ant используется для компиляции, развертывания и выполнения кода.
Ant можно скачать с сайта Apache Веб-сайт.
Файл Build.xml, используемый для настройки целей выполнения с помощью Ant.
Ant можно запустить из командной строки или из подходящего плагина IDE, например eclipse.