本文介绍了在TestNG中的@BeforeMethod和@AfterMethod之间共享驱动程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用testNG编写测试.每个测试方法共享在类级别存储的许多公共属性,但是每个测试方法都需要其自己的独立驱动程序,因此无法将驱动程序存储为类变量.这样一来,每种测试方法就可以在同时运行时被不同的驱动程序多次调用.

基本上,我要执行的操作的sudo代码如下所示:

@BeforeMethod
public void setup(Argument someArg) {
    Driver driver = new Driver(argArg); 
}

@Test
public void test() {
    driver.dostuff();
}

@AfterMethod (alwaysrun = true)
public void teardown() {
    driver.quit();
}

我的想法是,我可能会使用类名和测试方法作为存储和检索驱动程序的键,将驱动程序存储在并发映射集合中,但是我想找到一种更简单,更轻松的方法./p>

很抱歉,如果有答案已经解决了.我四处搜寻,找不到我正在寻找的解决方案,或者无法将某个特定想法如何应用于我的问题.我的案例是针对Selenium Webdriver的,但是我想还有其他案例可能想要做这样的事情.

解决方案

如何使用ThreadLocal<Driver>?

I am writing tests in testNG. Each test method shares a number of common attributes stored at the class level but each test method needs its own independent driver, so the driver cannot be stored as a class variable. This allows each test method to be invoked multiple times with different drivers while running concurrently.

Basically my sudo-code of what I am trying to do would look something like the following:

@BeforeMethod
public void setup(Argument someArg) {
    Driver driver = new Driver(argArg); 
}

@Test
public void test() {
    driver.dostuff();
}

@AfterMethod (alwaysrun = true)
public void teardown() {
    driver.quit();
}

My thought is that I might store the drivers in a concurrent map collection using the classname and test method as a key for storing and retrieving the driver, but I would like to find a simpler, less verbose way of doing this.

I apologize if there is an answer that already addresses this. I searched high and low and couldn't find the solution I was looking for or couldn't make the connection to how a specific idea would apply to my problem. My case is specific to Selenium Webdriver, but I imagine that there are other cases that may want to do something like this.

解决方案

How about using a ThreadLocal<Driver>?

这篇关于在TestNG中的@BeforeMethod和@AfterMethod之间共享驱动程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 05:23