java - 如何在selenium的testng中静态打开浏览器(所有测试都在一个浏览器中)

标签 java selenium selenium-webdriver automation testng

我在我的项目中使用 selenium 和 testNG 框架。 现在发生的事情是每个类都打开一个浏览器,然后运行它的方法,例如,如果我有五个类,那么五个浏览器将同时打开,然后运行测试。 我想在开始时打开浏览器一次并运行所有方法,然后关闭它。

public class openSite
{
public static WebDriver driver;
@test
public void openMain()
{
  System.setProperty("webdriver.chrome.driver","E:/drive/chromedriver.exe");
  WebDriver driver = new ChromeDriver();
  driver.get("http://vtu.ac.in/");
}
@test
//Clicking on the first link on the page
public void aboutVTU()
{
driver.findElement(By.id("menu-item-323")).click();
}
@Test
//clicking on the 2nd link in the page
public void Institutes()
{
driver.findElement(By.id("menu-item-325")).click();
}

现在我想要的是 testNG 应该打开浏览器一次并打开 vtu.ac.in 一次,然后执行 aboutVTU 和 Institutes 的方法并给我结果

最佳答案

您已经在字段声明中声明了 driver 的类型。在 openMain() 中重新声明它是您的问题。它应该看起来像这样。

import static org.testng.Assert.assertNotNull;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class OpenSite {
    private WebDriver driver;

    @BeforeClass(alwaysRun=true)
    public void openMain()
    {
      System.setProperty("webdriver.chrome.driver","/usr/local/bin/chromedriver");
      driver = new ChromeDriver();
      driver.get("http://vtu.ac.in/");
    }

    @Test
    //Clicking on the first link on the page
    public void aboutVTU()
    {
        assertNotNull(driver);
        driver.findElement(By.id("menu-item-323")).click();
    }

    @Test(dependsOnMethods="aboutVTU")
    //clicking on the 2nd link in the page
    public void Institutes()
    {
        assertNotNull(driver);
        driver.findElement(By.id("menu-item-325")).click();
    }
}

关于java - 如何在selenium的testng中静态打开浏览器(所有测试都在一个浏览器中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26114562/

相关文章:

java - 升级到 Log4J2 面临异常。 [Java.lang.ClassNotFoundException : org. apache.logging.log4j.LogManager]

java - 将自定义属性添加到 JTree 节点

python - Selenium 类型错误 : __init__() takes 2 positional arguments but 3 were given

selenium-webdriver - Chromedriver 79.0.3945.88。存在?

Java:.equals() 对于集合失败(JGraphT)

java - 学习线程的资源

python - 类型错误 : 'str' object is not callable error using text() from Selenium Python

selenium - 通过 marionette 驱动程序在 Firefox 浏览器中设置代理

python - 我需要明确等待吗?

javascript - 定位器无效错误