如何对字符串变量使用threadlocal并在并行类执行期间存储不同的运行时值?我面临多个问题

问题描述 投票:0回答:1

问题1:我有一个变量“名称”,它将具有一些运行时值,并且我在跨包的类中使用该值,而且我无法在方法中返回该值,因为我已经返回布尔值。该变量包含相同的值值,它在每个类别中都不会改变。 预期:它应该包含不同类执行的不同值,并且不应覆盖

我尝试过以下:

public static commonClass {
protected static ThreadLocal<String> stringThreadLocal=new ThreadLocal<>();
public static String name=null;

public static boolean getName()
{
//---some code here---

name = driver.findElement(By.id(element)).getText()
stringThreadLocal.set(tempname);
name=getString();
//---- some code here----
return flag;
}

public static String getString(){

return stringThreadLocal.get();

}
}

我需要在@beforeclass方法中使用它的测试类:

public class Class1{

String searchName = null;

@BeforeClass(alwaysRun = true)
@Parameters("browser")
public void verifyConnectJourneyBuilderUI(String browser) throws Exception {
flag=commonClass.getName();
assertEquals(flag, true);       
System.out.println("created with name:"+ commonClass.name);
searchName= commonClass.getString();  
}
}

在每个类执行中都会生成一个新名称,但有时所有线程都采用相同的名称,并且我在“name”和“searchName”变量中获得相同的值。

我在(如何在并行执行selenium java中存储运行时变量?)提到了类似的问题,但无法得到正确的解决方案。有人可以建议一些吗?

ISSUE2:有时 TC 会失败,因为一个线程找不到类的“名称”。 我假设如果一个类中的 TC 被执行并且一个线程变得空闲,那么两个线程都将在另一个类上工作,并且两个线程都将具有不同的值,但由于我正在删除 @afterclass 中“name”中包含的元素,因此该元素在一个类的 @afterclass 中删除,那么下一类 TC 将找不到它。我的理解正确吗?

multithreading selenium-webdriver variables testng parallel-testing
1个回答
0
投票

我绝不会建议在新代码中使用

ThreadLocal
。当您有使用
static
变量的旧单线程代码,并且需要将其移植到多线程环境中时,请使用它。如果将
static Foobar
变量替换为
static final ThreadLocal<Foobar>
变量,这是让程序中的多个线程使用旧代码的简单方法,只要每个线程以旧的单线程方式使用它即可。

我无法在方法中返回这个值,因为我已经返回布尔值了

这就是复合类型的用途。为什么不这样做呢?

public static commonClass {

    public class Result {
        public final String name;
        public final boolean flag;
        public Result(String name, boolean flag) {
            this.name = name;
            this.flag = flag;
        }
    }

    public static Result getString(){
    {
        //---some code here---
        String name = driver.findElement(By.id(element)).getText()
        name=getString();
        //---- some code here----
        return new Result(name, flag);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.