JUnit在测试后清除实例变量

时间:2014-06-01 19:59:23

标签: java selenium junit webdriver junit4

我有这个非常简单的测试,如下所示,但是有一个问题。在第一次测试" A_login"我导航到特定页面并获取表的内容,并将此内容存储在ArrayList中。当第一次测试完成后,我想使用我在第二次测试中收集的数据,但是当我尝试使用它或打印出列表时,它是空的。有什么好理由吗?似乎JUnit清除了实例变量。我怎样才能做到这一点?

public class Crawl extends Driver {

private static WebDriver driver;
private List<String> table_data;

public Crawl() {
    super();
    this.driver = super.getDriver();
    this.table_data = new ArrayList<String>();
}

/*
    Login and get all open orders
*/
@Test
public void A_login() {
    this.driver.get("http://www.xxxx.no/xxxx/");
    this.driver.findElement(By.id("username")).sendKeys("Username");
    this.driver.findElement(By.id("password")).sendKeys("Password");
    this.driver.findElement(By.xpath("/html/body/div[2]/div/div/form/fieldset/div[4]/div/input[2]")).click();
    this.driver.get("http://www.xxxxx.no/xxxx/shops_invoice.php");

    WebElement table = this.driver.findElement(By.xpath("/html/body/div/div[2]/div[2]/table/tbody"));
    List<WebElement> tr_collection = table.findElements(By.tagName("tr"));

    for(int i = 0; i < tr_collection.size() ; i++){
        this.table_data.add((tr_collection.get(i).getText());
    }
}

@Test
public void B_getCustomerInfo() {
    System.out.println(this.table_data);
}

@AfterClass
public static void tearDown() { driver.quit(); }

}

1 个答案:

答案 0 :(得分:2)

这就是JUnit的工作原理。对于它运行的每个测试方法,它会创建测试类的新实例,运行测试并抛出测试类实例。这是故意的:测试应该彼此隔离。

Martin Fowler在此更详细地解释了这一点:http://martinfowler.com/bliki/JunitNewInstance.html

不要做你正在尝试做的事情,而是编写一个填充表并从两个测试中调用它的方法。