JUnit4测试用例将无法继续 [英] JUnit4 test case won't continue

查看:118
本文介绍了JUnit4测试用例将无法继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Selenium IDE创建了一个包含2个测试用例的测试套件.我将该套件导出为Java/JUnit4/WebDriver.

I created a test suite with 2 test cases using Selenium IDE. I exported the suite as Java/JUnit4/WebDriver.

第一个测试用例允许用户登录站点,找到匹配项后进行成员搜索,访问成员的个人资料

the first test case allow user to log-in the site, do a member search after the match is found, access the member's profile

第二个测试用例:在成员资料中,单击捐赠"链接以添加承诺.

the second test case: once in the member profile, click on the link 'donation' to add a pledge.

该测试套件在Selenium IDE中运行良好,但是当我执行该套件时,它在Eclipse中挂断了. 行为在Eclipse中,第一个测试用例运行良好,第二个用例打开一个新的浏览器,系统需要登录(输入用户名和密码).

The test suite runs fine in Selenium IDE, but it hang up in Eclipse when I executed the suite. behavior in Eclipse, the first test case runs fine, the 2nd case opens up a new browser, the system required log-in (enter username and password).

我想知道该怎么办,因此测试用例2继续进行,而无需要求用户登录. 感谢您的帮助和建议.

I would like to know what shall I do, so the test cases 2 continues without asking user to log-in. I appreciate your help and advises.

这是我的测试套件代码,分为3部分(由于该站点是内部站点,因此删除了uid和pd)

Here is my test suite code break down into 3 sections (I removed uid and pd, due to the site is a internal site)

-test suite runner file: searchDonorAddPledge   
-test case1: searchDonorSuzy.class    
-test case2: DonorAddPledge.class

故障跟踪消息:

  1. org.openqa.selenium.StaleElementReferenceException:元素不 在缓存中找到-自从 查找命令持续时间或超时:30.12秒

  1. org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up Command duration or timeout: 30.12 seconds

原因: org.openqa.selenium.remote.ErrorHandler $ UnknownServerException: 在缓存中找不到元素-自此以来页面可能已更改 它被查找Build info:version:'2.31.0',version:'1bd294d', 时间:"2013-02-27 20:53:56"

Caused by: org.openqa.selenium.remote.ErrorHandler$UnknownServerException: Element not found in the cache - perhaps the page has changed since it was looked up Build info: version: '2.31.0', revision: '1bd294d', time: '2013-02-27 20:53:56'

运行程序文件:

import org.junit.runners.Suite;
import org.junit.runner.RunWith;

      @RunWith(Suite.class)
      @Suite.SuiteClasses
      (
        {
            SearchDonorSuzy.class,
            DonorAddPledge.class      
        }
      )

      public class searchDonorAddPledge { }

测试用例1代码:

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class SearchDonorSuzy 
{
    private WebDriver driver;
      private String baseUrl;
      private boolean acceptNextAlert = true;
      private StringBuffer verificationErrors = new StringBuffer();

      @Before
      public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "https://jlaustin.tcheetah.com/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      }

      @Test
      public void testSearchDonorSuzy() throws Exception {
        // set overall speed of the test case
        // ERROR: Caught exception [ERROR: Unsupported command [setSpeed | 4000 | ]]
        driver.get(baseUrl + "/?html=openid");
        driver.findElement(By.cssSelector("input[type=\"submit\"]")).click();
        driver.findElement(By.id("edit-name")).clear();
        driver.findElement(By.id("edit-name")).sendKeys("username");
        driver.findElement(By.id("edit-pass")).clear();
        driver.findElement(By.id("edit-pass")).sendKeys("password");
        driver.findElement(By.id("edit-submit")).click();
        driver.findElement(By.id("cmp_admin")).click();
        driver.findElement(By.id("quicksearch_anchor")).click();
        driver.findElement(By.cssSelector("img[alt=\"Member\"]")).click();
        driver.findElement(By.id("search_name")).clear();
        driver.findElement(By.id("search_name")).sendKeys("suzy");
        driver.findElement(By.cssSelector("input[type=\"image\"]")).click();
        driver.findElement(By.linkText("Balagia, Suzy")).click();
      }

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

      private boolean isElementPresent(By by) {
        try {
          driver.findElement(by);
          return true;
        } catch (NoSuchElementException e) {
          return false;
        }
      }

      private String closeAlertAndGetItsText() 
      {
        try 
        {
          Alert alert = driver.switchTo().alert();
          if (acceptNextAlert) 
          {
            alert.accept();
          } 
          else 
          {
            alert.dismiss();
          }
          return alert.getText();
        } 
        finally 
        {
          acceptNextAlert = true;
        }
      }

}

testcase2代码:

import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class DonorAddPledge 
{
      private WebDriver driver;
      private String baseUrl;
      private boolean acceptNextAlert = true;
      private StringBuffer verificationErrors = new StringBuffer();

      @Before
      public void setUp() throws Exception 
      {
        driver = new FirefoxDriver();
        baseUrl = "https://jlaustin.tcheetah.com/";
        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
      }

      @Test
      public void testDonorAddPledge() throws Exception 
      {
        driver.get(baseUrl + "/?nd=db_member&account_id=942&nowwritestate=i1110536420226242");

        driver.findElement(By.xpath("(//a[contains(text(),'Donor')])[2]")).click();
        driver.findElement(By.linkText("Campaign Manager")).click();
        new Select(driver.findElement(By.id("campaign_id"))).selectByVisibleText("A Christmas Affair 2012");
        driver.findElement(By.xpath("//a[contains(text(),'Add\n            pledge')]")).click();
        driver.findElement(By.id("pledge_amount")).clear();
        driver.findElement(By.id("pledge_amount")).sendKeys("100.00");
        driver.findElement(By.id("pledge_notes")).clear();
        driver.findElement(By.id("pledge_notes")).sendKeys("test pledge");
        driver.findElement(By.cssSelector("input[type=\"image\"]")).click();
      }

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

      private boolean isElementPresent(By by) 
      {
        try 
        {
          driver.findElement(by);
          return true;
        } 
        catch (NoSuchElementException e) 
        {
          return false;
        }
      }

      private String closeAlertAndGetItsText() 
      {
        try 
        {
          Alert alert = driver.switchTo().alert();
          if (acceptNextAlert) 
          {
            alert.accept();
          } 
          else 
          {
            alert.dismiss();
          }
          return alert.getText();
        }

        finally 
        {
          acceptNextAlert = true;
        }
      }

}

推荐答案

两个测试用例都在其@Before方法中实例化了一个新的驱动程序;这会以一个新的会话启动一个新的浏览器实例,因此它将丢失任何先前测试用例的已登录会话详细信息:

Both testcases instantiate a new driver in their @Before method; this starts a new browser instance with a fresh session, so it loses the logged-in session details from any previous testcase:

driver = new FirefoxDriver();

我建议您研究两种替代策略:

I'd recommend looking into two alternative strategies:

  1. 每个类一次实例化驱动程序,并将测试用例放入依赖于使用同一会话的同一类中.
  2. 重组您的测试用例,使它们彼此独立.

1.在多个测试用例中保持相同的会话

通过每个类仅实例化一次驱动程序,而不是针对每个测试用例单独实例化驱动程序,可以提高代码执行效率.但是,您应该认为这主要是为了节省效率;我不建议使用它作为将测试用例链接在一起的方式,例如,使测试用例2依赖于成功运行的测试用例1.

1. Keeping the same session across multiple testcases

You can make your code execution more efficient by instantiating the driver only once per class, instead of separately for every testcase. You should think of this as mainly an efficiency saving, however; I don't recommend using it as a way of linking the testcases together so that testcase 2 relies on testcase 1 having run successfully, for example.

总是很想按顺序构造测试用例,因此您要进行测试用例1(例如,包括登录),并自然而然地进入测试用例2(它还要执行一些进一步的操作).但是我警告这会导致问题.这会使您的整个测试套件变得更加脆弱-如果测试用例1中存在问题,则所有随后的测试用例都将失败.它使测试的灵活性降低-您不能只运行测试用例3来单独进行重新测试,也不能从套件中选择单个测试用例.

It's always tempting to construct testcases in sequence, so that you do testcase 1 (which includes logging in, for example) and that leads naturally on to testcase 2 (which does some further actions). However I'd warn that this will lead to problems. It makes your whole test suite more fragile - if there's a problem in testcase 1, all the testcases afterwards fail. It makes your testing less flexible - you can't just run testcase 3 to retest in isolation, and you can't pick and choose individual testcases out of the suite.

我强烈建议您研究第二种策略;因此,例如,如果测试用例1仅在测试登录例程,则使其仅测试登录例程,然后再次注销.而且,如果测试用例2仅测试了一些仅在登录后才能实现的功能-很好,请使其登录,以便可以获取其感兴趣的功能.测试用例1确实也可以登录的事实与测试用例2无关紧要,这也不是问题-实际上,您可以将其视为开始重构测试用例以将重复的代码提取到单独的方法调用中的机会.

I'd strongly recommend you look into the second strategy; so for example if testcase 1 is just testing the login routine, have it just test the login routine and then log out again. And if testcase 2 is just testing some functionality which can only be reached after login - well, make it log in so it can get to the functionality it's interested in. The fact that testcase 1 also does log in is not really relevant to testcase 2, and it's not a problem either - in fact, you can see it as an opportunity to start re-factoring your testcases to extract repeated code into a separate method call.

这篇关于JUnit4测试用例将无法继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆