Selenium - первые шаги
Ну раз я тут в банке занимаюсь тестированием (блять, стыдно аж) то надо показать публике как это делается. Я уже выкладывал на форуме теперь надо выложить тут с пояснениями.
Selenium эта такая система которая позволяет писать автоматические тесты. То есть пишется программа которая умеет ходить по сайту, нажимать ссылки и заполнять формы. В идеале Selenium должен работать со всеми браузерами но на практике его удалось заставить работать только с IE. Фактически Selenium открывает окно браузера и при помощи XPath ищет элементы на страницы или ищет просто текст для сравнения. Но для того чтобы что-то написать Selenium сначала нужно установить и сконфигурировать.
Сначала я покажу как написать Maven конфиг
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>ua.kiev.mabp</groupId>
<artifactId>HelloWorld</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>HelloWorld</name>
<url>http://localhost/</url>
<description>Demo version</description>
<developers>
<developer>
<id>mabp</id>
<name>CTAPbIu_MABP</name>
<organization>mabp.kiev.ua</organization>
<email>ctapbiumabp@gmail.com</email>
</developer>
</developers>
<contributors>
<contributor>
<name>CTAPbIu_MABP</name>
<organization>mabp.kiev.ua</organization>
<email>ctapbiumabp@gmail.com</email>
</contributor>
</contributors>
<repositories>
<repository>
<id>openqa-releases</id>
<name>Openqa Release Repository</name>
<url>http://nexus.openqa.org/content/repositories/releases</url>
<layout>default</layout>
<snapshots>
<enabled>false</enabled>
</snapshots>
<releases>
<enabled>true</enabled>
</releases>
</repository>
<repository>
<id>openqa-snapshots</id>
<name>Openqa Snapshot Repository</name>
<url>http://nexus.openqa.org/content/repositories/snapshots</url>
<layout>default</layout>
<snapshots>
<enabled>true</enabled>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</snapshots>
<releases>
<enabled>false</enabled>
</releases>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.openqa.selenium.client-drivers</groupId>
<artifactId>selenium-java-client-driver</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>selenium-maven-plugin</artifactId>
<executions>
<execution>
<phase>pre-integration-test</phase>
<goals>
<goal>start-server</goal>
</goals>
<configuration>
<background>true</background>
</configuration>
</execution>
</executions>
<configuration>
<browser>*iexplore</browser>
<startURL>http://pyha.ru:80</startURL>
<suite>/forum/</suite>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<!-- Skip the normal tests, we'll run them in the integration-test phase -->
<skip>true</skip>
</configuration>
<executions>
<execution>
<phase>integration-test</phase>
<goals>
<goal>test</goal>
</goals>
<configuration>
<skip>false</skip>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Хотя мне так и не удалось запустить в работу таск seleniun:selenese, из-за ошибки
[ERROR] FATAL ERROR
[INFO] ------------------------------------------------------------------------
[INFO] Could not find matching constructor for: org.openqa.selenium.server.SeleniumServer(java.lang.Integer, java.lang.Boolean, java.lang.Boolean)
[INFO] -----------------------------------------------------------------------
Его все равно надо запускать чтобы подтянулись все зависимости. На форумах говорят что эта ошибка возникает из-за несовместимости selenium-maven-plugin и самого Selenium.
Но в общем это не важно потому что все запускается и так. Для начала надо таском selenium:start-server запустить сервер. После этого можно вызвать класс который я сейчас покажу как написать. Там все просто даже если никогда раньше не имел дела с JUnit.
package ua.kiev.mabp;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;
import junit.framework.TestCase;
/**
* Created by IntelliJ IDEA.
* User: CTAPbIu_MABP
* Date: 30.04.2009
* Time: 14:08:50
*/
public class PyhaTestCase extends TestCase {
private Selenium selenium;
String url = "http://pyha.ru/forum/";
public void setUp() {
selenium = new DefaultSelenium("localhost", 4444, "*iexplore", url);
selenium.start();
}
public void testValidRegisration() {
try {
selenium.open(url);
selenium.type("//input[@name='user']", "CTAPbIu_MABP");
selenium.type("//input[@name='passwrd']", "******");
selenium.click("//input[@value='войти']");
selenium.waitForPageToLoad("20000");
selenium.click("//a[@href='http://pyha.ru/forum/board/19.0']"); // флейм
selenium.waitForPageToLoad("20000");
selenium.click("link=Новая тема"); // так тоже можно
selenium.waitForPageToLoad("20000");
selenium.type("//input[@name='subject']", "Selenium");
selenium.type("//textarea[@name='message']", "Эта тема была создана с использованием Selenium 1.0, Maven 2.10, Intellij IDEA 8.1 и JDK 1.6u13 :)");
selenium.click("//input[@name='post']");
} catch (Exception e) {
e.printStackTrace();
}
}
public void tearDown() {
selenium.stop();
}
}
Вот такой небольшой класс позволяющий залогиниться на форум Pyha.ru под фейковым аккаунтом и создать новую тему в разделе "флуд".
По большому счету это все, больше ничего прикручивать не надо и плясать с бубеном тоже.
Свежие комментарии