在Selenium IntelliJ中运行每个测试用例后如何关闭窗口?

时间:2015-07-18 01:25:23

标签: selenium intellij-idea

我有一组三个测试用例,我想避免保持打开多个浏览器窗口,因为我在Selenium中自动化了这个过程。有没有办法在每个测试用例完成后关闭浏览器而不会出错?

使用close()和quit()都会给我错误代码1。

1 个答案:

答案 0 :(得分:2)

我们使用以下方法来处理这些问题。

1)创建一个基类,它具有beforeSuite,beforeTest,afterTest,afterSuite方法,它们将始终运行。

2)每个测试计划都应扩展此类以创建驱动程序并关闭驱动程序。

BasePage.java

echo gettype($test); // "object"
echo $test->name; // "test"

Testplan.java

 package com.test.test3;

 import java.lang.reflect.Method;
 import java.util.Date;

 import org.openqa.selenium.WebDriver;
 import org.testng.annotations.AfterMethod;
 import org.testng.annotations.AfterSuite;


public class BasePage {

public WebDriver driver = null;

private Date start;

/*
 * Below method will initialize the driver once test method started
 * execution
 */
public void initializeDriver(WebDriver driver) {

    this.driver = driver;

}

/*
 * Below method will kill driver
 */
public void tearDown() {

    if (this.driver != null) {
        this.driver.quit();
    }

}

@AfterMethod(alwaysRun = true)
public void afterTestMethod(Method method) {

    // Clean ups for test level services
    tearDown();

}

@AfterSuite(alwaysRun = true)
public void afterTestSuite() {

    tearDown();

}


}

的testng.xml

package com.test.test3;

import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;

public class TestPlan extends BasePage{

@Test(groups = { "test"})
public void test() {

    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    System.out.println("TestAutomation test");
}

@Test(groups = { "test"})
public void test1() {
    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    System.out.println("TestAutomation test");
}

@Test(groups = { "test"})
public void test2() {
    FirefoxDriver driver = new FirefoxDriver();
    driver.get("http://www.google.com");
    System.out.println("TestAutomation test");
}

}