简体   繁体   中英

Get ThreadLocal Variable In Different Classes - Java - Selenium WebDriver

How do I get use a ThreadLocal value that was set in a different class?

Example, I set these variables in class A:

ThreadLocal<String> username = new ThreadLocal<String>();
username.set("user");

ThreadLocal<String> password = new ThreadLocal<String>();
password.set("pass");

I know how to "get" them from within the same class by doing:

String myUsername = username.get();
String myPassword = password.get();

But I can't find anything on how I would use/get them in Class B?

The basic end goal is I am trying to convert my Selenium WebDriver tests to run in parallel. These text values will get entered in one class (A), but then I have another class (B) that contains "methods" that get called upon (check database entries, verify on screen data, etc.) that would need to know the data that was entered in class (A).

The way I am doing this for non-ThreadLocal variables successfully is like this:

Set the value in class A:

@Test (priority = 1)
public void enterData() {

    String environment = "QA";

    // Pass environment to stored variables
    StoredVariables newEnv = new StoredVariables();
    newEnv.setEnv(environment);

    driver.enterData;

}

Store it in class B (StoredVariables):

public class StoredVariables {

    private static String environment = "";

    public StoredVariables() {

    }

    public static String getEnv() {return environment;}
    public void setEnv(String s) {environment = s;}

}

Access it from class C:

@Test (priority = 1)
public void verifyData() {

    String environment = StoredVariables.getEnv();

}

First of all I am not fan of TestNG. Parallel running tests is also possible with JUnit if you configure Surefire to run them parallel or if you use Parallel runner. Consider probably changing to JUnit.

If you stick to selenium, then you can create a ITestListener implementation. This class can have a static ThreadLocal. This should store the WebDriver used by the test. You create a static method, which gives back the ThreadLocal value for test classes. In onTestStart method you can take care of starting the browser, in onTestSuccess you can stop the browser, in onTestFailure you can take screenshot, save HTML and logs, and stop the browser.

Also take care, that you use the PageObject pattern.

Think of a ThreadLocal<T> as a Map<Thread,T> . It's not meant as a way of sharing values between classes, but a way of maintaining different values in each thread.

The way you pass this variable around is exactly the same as you would any other variable. Usually by returning it somewhere and/or storing it as a field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM