2013-11-19 6 views
1

это мой первый пост здесь. Прошло всего пару дней с тех пор, как я начал использовать Selenium с Arquillian, чтобы протестировать наш сайт ... soo, пожалуйста, будьте терпеливы, потому что мне все еще не хватает знаний ...Selenium, Arquillian, Eclipse: попытка сделать тест подождать, пока страница не будет полностью загружена

Я пытаюсь сделать логин- теста, введя четыре различные комбинации имени пользователя и пароля. Три из них неверны, веб-сайт должен показывать сообщение об ошибке, когда эти имя пользователя и пароль отправляются. Тест должен проверить, действительно ли отображается сообщение об ошибке. Обратите внимание, что сообщение об ошибке - это просто текстовое поле на одном и том же веб-сайте (не всплывающее окно или что-то в этом роде)

Прежде чем вводить следующую комбинацию имени пользователя/пароля, я хотел бы обновить сначала. В противном случае тест всегда будет обнаруживать сообщение об ошибке из предыдущей записи. Проблема в том, что тест просто прекращается после отправки первого имени пользователя/пароля и обновления страницы. В JUnit я получил это сообщение об ошибке: «org.openqa.selenium.StaleElementReferenceException:« Элемент не найден в кеше - возможно, страница изменилась с момента его поиска ».

Я предполагаю, что после обновления теста подождите несколько секунд, пока страница не будет полностью загружена .. Но если я использую что-то вроде «fluentWait» с «findElement (By.id (« user_name »)). Тест продолжится (он не будет ждать), потому что оба сессий те же веб-сайт (до обновления и после обновления) и идентификатор «user_name», конечно, всегда есть ...

я был бы очень признателен за любую помощь :)

package org.xxyy.uitest; 

import static org.junit.Assert.*; 

import java.util.concurrent.TimeUnit; 

import org.jboss.arquillian.drone.api.annotation.Drone; 
import org.jboss.arquillian.junit.Arquillian; 
import org.junit.After; 
import org.junit.Before; 
import org.junit.BeforeClass; 
import org.junit.Test; 
import org.junit.runner.RunWith; 
import org.openqa.selenium.By; 
import org.openqa.selenium.WebElement; 
import org.openqa.selenium.NoAlertPresentException; 
import org.openqa.selenium.WebDriver; 

//import org.openqa.selenium.firefox.FirefoxDriver; 

@RunWith(Arquillian.class) 
public class LoginTest { 

    static String baseUrl; 
    private StringBuffer verificationErrors = new StringBuffer(); 

    @Drone 
    WebDriver driver; 

    @BeforeClass 
    public static void setUp() throws Exception { 
     baseUrl = "http://team-xxyy.intern/"; 
    } 

    @Before 
    public void beforeTest() throws Exception { 
     driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); 
     driver.get(baseUrl + "xxyy/login.html"); 
    } 

    @Test 
    public void fehlLogin1() throws Exception { 


     WebElement username = driver.findElement(By.id("user_name")); 
     WebElement password = driver.findElement(By.id("user_password")); 

     username.clear(); 
     username.sendKeys("blume"); 
     password.clear(); 
     password.sendKeys("homersimpson"); 
     driver.findElement(By.id("login_submit")).click(); 
     Thread.sleep(2000); 
     verifyLoginInfo("blume", "homersimpson"); 

    } 

    @Test 
    public void fehlLogin2() throws Exception { 


     WebElement username = driver.findElement(By.id("user_name")); 
     WebElement password = driver.findElement(By.id("user_password")); 

     username.clear(); 
     username.sendKeys("blume"); 
     password.clear(); 
     password.sendKeys("jill"); 
     driver.findElement(By.id("login_submit")).click(); 
     Thread.sleep(2000); 
     verifyLoginInfo("blume", "jill"); 

    } 

    @Test 
    public void fehlLogin3() throws Exception { 

     WebElement username = driver.findElement(By.id("user_name")); 
     WebElement password = driver.findElement(By.id("user_password")); 

     username.clear(); 
     username.sendKeys("jack"); 
     password.clear(); 
     password.sendKeys("homersimpson"); 
     driver.findElement(By.id("login_submit")).click(); 
     Thread.sleep(2000); 
     verifyLoginInfo("jack", "homersimpson"); 

    } 

    @Test 
    public void fehlLogin4() throws Exception { 


     WebElement username = driver.findElement(By.id("user_name")); 
     WebElement password = driver.findElement(By.id("user_password")); 

     username.clear(); 
     username.sendKeys("jack"); 
     password.clear(); 
     password.sendKeys("jill"); 
     driver.findElement(By.id("login_submit")).click(); 
     Thread.sleep(2000); 
     verifyLoginInfo("jack", "jill"); 

    } 

    @After 
    public void tearDown() throws Exception { 
     driver.quit(); 
     String verificationErrorString = verificationErrors.toString(); 
     if (!"".equals(verificationErrorString)) { 
      fail(verificationErrorString); 
     } 
    } 

    private void verifyLoginInfo(String user_name, String user_password) { 

     if (user_name.equals("jack") 
       && user_password.equals("jill") 
       && driver.getCurrentUrl().startsWith(
         "https://global.something.com/login/123456789/")) { 
      System.out 
        .println("XXYY bitte manuell einloggen. Test wird abgebrochen"); 
      return; 

     } 

     if (user_name.equals("jack") && user_password.equals("jill")) { 

      if (isForwardSuccessful()) { 
       System.out.println("Eingabe: Username = " + user_name 
         + ", Passwort = " + user_password); 
       System.out.println("Korrekt-Login: Erfolgreich!"); 
       return; 
      } else { 
       System.out.println("Eingabe: Username = " + user_name 
         + ", Passwort = " + user_password); 
       System.out 
         .println("Korrekt-Login: Trotz korrekter Benutzername und Passwort ist Login fehlgeschlagen."); 
       return; 
      } 
     } 

     if (isAlertPresent()) { 
      System.out.println("Eingabe: Username = " + user_name 
        + ", Passwort = " + user_password); 
      System.out.println("Fehl-Login: Erfolgreich!"); 
      return; 

     } else { 
      System.out.println("Eingabe: Username = " + user_name 
        + ", Passwort = " + user_password); 
      System.out 
        .println("Fehl-Login: Fehlermeldung wird nicht angezeigt."); 
      return; 

     } 

    } 

    private boolean isAlertPresent() { 
     try { 
      assertEquals(
        "Der Benutzername oder das Passwort sind nicht korrekt. Bitte versuchen Sie es erneut.", 
        driver.findElement(
          By.cssSelector("#password-message > span.message")) 
          .getText()); 
      return true; 
     } catch (NoAlertPresentException e) { 
      return false; 
     } 
    } 

    private boolean isForwardSuccessful() { 
     try { 
      assertEquals(
        "http://team-xxyy.intern/xxyy/index.html", 
        driver.getCurrentUrl()); 
      return true; 
     } catch (Error e) { 
      verificationErrors.append(e.toString()); 
      return false; 
     } 

    } 

} 

pom.xml

<?xml version="1.0" encoding="UTF-8"?> 
<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/xsd/maven-4.0.0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 

    <groupId>org.xxyy.uitest</groupId> 
    <artifactId>xxyy-ui-test</artifactId> 
    <version>1.0-SNAPSHOT</version> 
    <packaging>jar</packaging> 

    <name>xxyy-ui-test</name> 
    <url>http://maven.apache.org</url> 

    <properties> 
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 
     <!-- 20131112 die beiden Zeilen unten wurden neu hinzugefügt von "https://docs.jboss.org/author/display/ARQ/Drone" --> 
     <version.org.jboss.arquillian>1.1.1.Final</version.org.jboss.arquillian> 
     <version.org.jboss.arquillian.drone>1.2.0.CR1</version.org.jboss.arquillian.drone> 
    </properties> 
    <dependencyManagement> 
     <dependencies> 
      <dependency> 
       <groupId>org.jboss.arquillian</groupId> 
       <artifactId>arquillian-bom</artifactId> 
       <version>${version.org.jboss.arquillian}</version> 
       <scope>import</scope> 
       <type>pom</type> 
      </dependency> 
      <dependency> 
       <groupId>org.jboss.arquillian.extension</groupId> 
       <artifactId>arquillian-drone-bom</artifactId> 
       <version>${version.org.jboss.arquillian.drone}</version> 
       <type>pom</type> 
       <scope>import</scope> 
      </dependency> 
     </dependencies> 
    </dependencyManagement> 
    <build> 
     <plugins> 
      <plugin> 
       <groupId>org.apache.maven.plugins</groupId> 
       <artifactId>maven-compiler-plugin</artifactId> 
       <!-- 20131113 Version hab ich erstmal rauskommentiert --> 
       <!-- version2.3.2version--> 
       <configuration> 
        <source>1.6</source> 
        <target>1.6</target> 
       </configuration> 
      </plugin> 
     </plugins> 
    </build> 
    <dependencies> 
     <dependency> 
      <groupId>junit</groupId> 
      <artifactId>junit</artifactId> 
      <version>4.8.1</version> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.jboss.arquillian.junit</groupId> 
      <artifactId>arquillian-junit-container</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.jboss.arquillian.extension</groupId> 
      <artifactId>arquillian-drone-impl</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <!-- 20131112 ab hier neu hinzugefügt von "https://docs.jboss.org/author/display/ARQ/Drone" --> 
     <dependency> 
      <groupId>org.jboss.arquillian.extension</groupId> 
      <artifactId>arquillian-drone-webdriver-depchain</artifactId> 
      <version>${version.org.jboss.arquillian.drone}</version> 
      <type>pom</type> 
      <scope>test</scope> 
     </dependency> 
     <!-- bis hier --> 
     <dependency> 
      <groupId>org.jboss.arquillian.extension</groupId> 
      <artifactId>arquillian-drone-selenium</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.jboss.arquillian.extension</groupId> 
      <artifactId>arquillian-drone-selenium-server</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.seleniumhq.selenium</groupId> 
      <artifactId>selenium-java</artifactId> 
      <scope>test</scope> 
     </dependency> 
     <dependency> 
      <groupId>org.seleniumhq.selenium</groupId> 
      <artifactId>selenium-server</artifactId> 
      <scope>test</scope> 
      <exclusions> 
       <exclusion> 
        <groupId>org.mortbay.jetty</groupId> 
        <artifactId>servlet-api-2.5</artifactId> 
       </exclusion> 
      </exclusions> 
     </dependency> 
     <dependency> 
      <groupId>org.slf4j</groupId> 
      <artifactId>slf4j-simple</artifactId> 
      <version>1.6.4</version> 
      <scope>test</scope> 
     </dependency> 
    </dependencies> 
    <profiles> 
     <profile> 
      <id>arquillian-weld-ee-embedded</id> 
      <activation> 
       <activeByDefault>true</activeByDefault> 
      </activation> 
      <dependencies> 
       <dependency> 
        <groupId>org.jboss.spec</groupId> 
        <artifactId>jboss-javaee-6.0</artifactId> 
        <version>1.0.0.Final</version> 
        <type>pom</type> 
        <scope>provided</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.jboss.arquillian.container</groupId> 
        <artifactId>arquillian-weld-ee-embedded-1.1</artifactId> 
        <version>1.0.0.CR3</version> 
        <scope>test</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.jboss.weld</groupId> 
        <artifactId>weld-core</artifactId> 
        <version>1.1.5.Final</version> 
        <scope>test</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.slf4j</groupId> 
        <artifactId>slf4j-simple</artifactId> 
        <version>1.6.4</version> 
        <scope>test</scope> 
       </dependency> 
      </dependencies> 
     </profile> 
     <profile> 
      <id>arquillian-glassfish-embedded</id> 
      <dependencies> 
       <dependency> 
        <groupId>org.jboss.arquillian.container</groupId> 
        <artifactId>arquillian-glassfish-embedded-3.1</artifactId> 
        <version>1.0.0.CR3</version> 
        <scope>test</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.glassfish.main.extras</groupId> 
        <artifactId>glassfish-embedded-all</artifactId> 
        <version>3.1.2</version> 
        <scope>provided</scope> 
       </dependency> 
      </dependencies> 
     </profile> 
     <profile> 
      <id>arquillian-jbossas-managed</id> 
      <dependencies> 
       <dependency> 
        <groupId>org.jboss.spec</groupId> 
        <artifactId>jboss-javaee-6.0</artifactId> 
        <version>1.0.0.Final</version> 
        <type>pom</type> 
        <scope>provided</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.jboss.as</groupId> 
        <artifactId>jboss-as-arquillian-container-managed</artifactId> 
        <version>7.1.1.Final</version> 
        <scope>test</scope> 
       </dependency> 
       <dependency> 
        <groupId>org.jboss.arquillian.protocol</groupId> 
        <artifactId>arquillian-protocol-servlet</artifactId> 
        <scope>test</scope> 
       </dependency> 
      </dependencies> 
     </profile> 
    </profiles> 
</project> 

arquillian.xml

<arquillian xmlns="http://jboss.com/arquillian" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://jboss.org/schema/arquillian http://jboss.org/schema/arquillian/arquillian_1_0.xsd"> 

    <extension qualifier="webdriver"> 
     <property name="browser">firefox</property> 
    </extension> 

</arquillian> 

ответ

0

Хорошо, несколько комментариев к вашему коду

  • driver = new FirefoxDriver(); - вы никогда не должны создать экземпляр драйвера самостоятельно, @Drone сделают это за вас
  • вы должны разделить свой тест на 4 метода (вы тестируете 4 тестовых примера, правильно?) И вводите метод, аннотированный с помощью @Before, который может обновлять страницу между тестами (или вызвать driver.get("baseUrl + "xxyy/login.html") - это сделает ваш код более четким и читаемым
  • вы также можете вытащить содержимое методов испытаний и положить его в какой-то метод Util, большая часть кода повторяется в каждом тесте, поэтому некоторые рефакторинга было бы хорошо здесь :)

Попробуйте, как это и посмотреть, что будет :)

+0

Привет, спасибо, что ответили так быстро! Я попытался реализовать изменения один за другим. Во-первых, я просто избавился от «driver = new FirefoxDriver();» и я заметил, что тест просто продолжался даже после ввода правильного имени пользователя/пароля. Когда я явно создаю экземпляр драйвера (firefox), тест фактически остановился после правильного имени пользователя/пароля, и браузер перешел на главную страницу (индекс) – user3006009

+0

.. и я не могу использовать @BeforeMethod. Я получаю «BeforeMethod» не может быть разрешен для типа «в Eclipse» – user3006009

+0

Это '@ Before' видит мое редактирование (' @ BeforeMethod' находится в TestNG) –

Смежные вопросы