3

我在自动化过程中使用 Junit 4 和 Selenium webdriver。我有多个测试用例,每个测试用例都需要登录功能。

我想在同一个浏览器窗口中运行所有测试用例并维护登录会话,而不是为每个测试用例打开新浏览器并每次都登录。(在我当前的脚本中,我在每个测试用例中启动 webdriver,它为每个测试用例打开一个新窗口并每次登录)

我想运行一个测试套件,我想在同一个浏览器窗口中运行我的所有测试用例。请给我一个解决方案。代码 :

public class first {
public static WebDriver driver;
@BeforeClass
public static void beforeClass()
{
    System.setProperty("webdriver.chrome.driver", "E:/chromedriver.exe");
    System.out.println("Before class");
    driver = new ChromeDriver();
}
@Test
public void login()throws Exception
{
        driver.get("URL");
    WebElement login = driver.findElement(By.xpath("my xpath");
    login.findElement(By.id("username")).sendKeys("username");
    login.findElement(By.id("password")).sendKeys("pwd");
    driver.findElement(By.xpath("my xpath")).click();
}

}

创建第二类:

public class second {
public static WebDriver driver;
{
@Test
public void nextstep()throws Exception
{
    WebElement buttons = driver.findElement(By.xpath("my xpath"));
    buttons.findElement(By.className("Classname")).click();

}

}

测试套件类:

@RunWith(Suite.class)
@SuiteClasses({first.class, second.class})
public class testsuite 
{
public static WebDriver driver;
@BeforeClass
public static void setUpClass()
{
    System.out.println("Master Setup");
}

}
4

2 回答 2

0

您需要实现一个套件设置方法,该方法打开一个新的浏览器窗口并登录。这样,该方法将在执行所有测试之前调用一次。

要将方法指定为套件设置方法,请将其放入套件类中,使其成为静态并使用注释@BeforeClass(请参阅此答案中的示例)。

在您发布的代码driver中,第一类中的driver变量和第二类中的变量不是同一个变量。这就是为什么在第一个类中初始化它确实会使driver第二个类中的 初始化并且你得到一个NullPointerException.
如果要在两个类中使用相同的变量,则需要定义一个具有非静态变量的基类driver(为什么首先将其设为静态?),然后从基类派生两个类。

于 2013-07-29T05:16:08.437 回答
-1
driver.get("URL");
WebElement login = driver.findElement(By.xpath("my xpath");

this code you have to put in @Before method instead of @Test so same session will continue

于 2013-11-14T06:46:03.207 回答