简体   繁体   English

使用ThreadLocal的FluentWait硒<RemoteWebDriver>

[英]FluentWait selenium using ThreadLocal<RemoteWebDriver>

I'm looking for a solution to implement FluentWaits in my java selenium test. 我正在寻找在Java硒测试中实现FluentWaits的解决方案。 The problem is that is use ThreadLocal to declare my drivers as thead-local to run them parallely. 问题是使用ThreadLocal将我的驱动程序声明为thead-local来并行运行它们。

Here is my code : 这是我的代码:

//My variable declaration
protected ThreadLocal<RemoteWebDriver> threadDriverFirefox = null;

//I create one for my thread in my BeforeTest
threadDriverFirefox = new ThreadLocal<RemoteWebDriver>();
threadDriverFirefox.set(new RemoteWebDriver(new URL(urlnode), DesiredCapabilities.firefox()));

//Add this method to get my driver
 public WebDriver driverFirefox() {
return threadDriverFirefox.get();
}

//And use it like this in my test
driverFirefox().get(weburl);

My problem is with the driverFirefox() I can't find a way to implement it in the FluentWait structure : 我的问题是在driverFirefox()上,我找不到在FluentWait结构中实现它的方法:

Wait waitfluent = new FluentWait(driverFirefox()).withTimeout(30, TimeUnit.SECONDS)
    .pollingEvery(2, TimeUnit.SECONDS).ignoring(NoSuchElementException.class);

WebElement testElement = waitfluent.until(new Function() {
    public WebElement apply(WebDriver driverFirefox() ) {
    return WebDriver driverFirefox().findElement(By.id("logEmailField"));
    }
});

But i've a syntax error... 但是我有语法错误...

Multiple markers at this line - Syntax error on token ")", delete this token - Syntax error on token(s), misplaced construct(s) 这行有多个标记-令牌“)”上的语法错误,删除此令牌-令牌上的语法错误,构造错误

Any idea to fix it ? 有解决的办法吗?

Thanks 谢谢

If you use a ThreadLocal, it should be static, otherwise you could introduce nasty memory leaks. 如果使用ThreadLocal,则它应该是静态的,否则可能会导致讨厌的内存泄漏。 And if the ThreadLocal is static, it should be accessed that way. 并且,如果ThreadLocal是静态的,则应该以这种方式访问​​它。 Further, as the reference is shared, you shouldn't initialize it by a thread (the reference) but only the value (calling set() ). 此外,由于引用是共享的,因此您不应通过线程(引用)对其进行初始化,而应仅通过值(调用set() )对其进行初始化。

public class TestContext {

  static ThreadLocal<WebDriver> CURRENT_DRIVER = new ThreadLocal<>();

  public static WebDriver currentDriver(){
    return CURRENT_DRIVER.get();
  }

   public void beforeTest(RemoteWebDriver driver) {
    CURRENT_DRIVER.set(driver);
   }
}

Now you can define the fluent wait using the shared driver: 现在,您可以使用共享驱动程序定义流畅的等待:

Wait waitfluent = new FluentWait(TestContext.currentDriver())
                      .withTimeout(30, TimeUnit.SECONDS)
                      .pollingEvery(2, TimeUnit.SECONDS)
                      .ignoring(NoSuchElementException.class);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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