【问题标题】:Test execution with multiple classes in TestNG using threads使用线程在 TestNG 中使用多个类进行测试执行
【发布时间】:2015-02-26 20:45:49
【问题描述】:

我试图在我的 TestNG 项目中运行多个类,但其中一个类总是失败。

AbstractTest.java (sampleTest1 和 sampleTest2 类只包含一对一的 @Test 和 get() 方法)

public class AbstractTest {

  private List<WebDriver> webDriverPool = Collections.synchronizedList(new ArrayList<WebDriver>());
  private ThreadLocal<WebDriver> driverThread;

  @BeforeTest
  public void beforeTest()
  {
    this.driverThread = new ThreadLocal<WebDriver>() {
      @Override
      protected WebDriver initialValue() {
        final WebDriver webDriver = new FirefoxDriver();
        webDriverPool.add(webDriver);
        return webDriver;
      }
    };
  }

  @AfterTest
  public void afterTest() {
    for (WebDriver driver : this.webDriverPool) {
      driver.quit();
    }
  }

  public WebDriver getDriver() {
    return this.driverThread.get();
  }

}

testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="11" name="testSuite" parallel="tests">
    <test name="Test1" group-by-instances="true">
        <classes>
            <class name="test.sample.sampleTest1" />
            <class name="test.sample.sampleTest2" />
        </classes>
    </test> <!-- Test1 -->
</suite> <!-- testSuite -->

问题是其中一个线程看不到 WebDriver,它返回 null 并且会失败。我知道如果我将 ThreadLocal 更改为 static 它会起作用,但如果我并行运行测试会导致更多问题,我的目标是什么 :)

提前致谢!

【问题讨论】:

  • getDriver() 应该是静态和同步的。当然只有当你想在具有相同状态的类之间共享它时。如果您需要单独的类和驱动程序,那么您也可以使用静态方法,但您需要 setter 为每个测试类设置新状态。
  • 能否请您写一下,我需要修改什么?我试过你写的,但还是不行。

标签: java selenium testng


【解决方案1】:

使用其他使用 ThreadLocal 的方法。例如一种线程安全的单例实现可以提供帮助:

public class DriverSession
{
    private static ThreadLocal<DriverSession> instance = new ThreadLocal<DriverSession>();
    private WebDriver                  driver;

    public static DriverSession getInstance()
    {
        if (null == instance.get())
        {
            instance.set(new Proxy1());
        }
        return instance.get();
    }

    protected DriverSession()
    {
        driver = new FirefoxDriver();
    }

    public WebDriver getDriver()
    {
        return this.driver;
    }
}

我就是这样做的。因此,为了访问当前的驱动程序实例,请使用:

DriverSession.getInstance().getDriver().get("http://google.com");

【讨论】:

  • 也许我的问题被误解了。所以...我想并行运行包含不同类的测试。我在@BeforeTest 中设置了浏览器,因为我想在同一个浏览器中按顺序而不是并行运行这些类。我使用 group-by-instances 的原因是我对类中的方法使用相同的优先级(例如,每个类都有 priority=1 方法),如果没有这个参数,就会出现问题。
  • 是的,我没明白你的意思。在这种情况下,您需要允许在线程内的类之间共享实例的东西。请查看更新的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
  • 1970-01-01
  • 2022-06-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多