简体   繁体   中英

dependency inject Selenium WebDriver with Spring?

Is it possible to use Spring to inject the WebDriver? I've read it can't be a singleton and should normally be instantiated during an @Before block. I'm ok with it being created at that point but I'd like to have it provided "magically" to some "helper" classes, instead of manually passing the reference to them.

update

I had it working fine locally with one test using

@DirtiesContext( classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)

but as soon as I put it on our server that runs concurrent tests and things I run into this error.

Singleton bean creation not allowed while the singletons of this factory are in destruction.

Using a Prototype isn't a good idea either because I also want to inject WebDriverBackedSelenium (which needs driver and ended up creating 2 instances) , and in some prototype cases I run into this.

nested exception is org.openqa.selenium.WebDriverException: Error forwarding the new session Request timed out waiting for a node to become available

Yes it is possible and works for me. In the context spring file you include the following:

<bean id="driver" class="org.openqa.selenium.firefox.FirefoxDriver"
destroy-method="quit">
</bean> 

Then in your class:

@Autowired
 private WebDriver adriver;
 public WebDriver getAdriver() {
    return adriver;
 } 

Please see this link for the more info

One way to mimic the @Before logic using Spring is to set the driver bean scope as prototype. This will create a new instance of driver per request. The problem is though if you want to use @Autowired on the helper classes that will create a new instance of webdriver.

To run tests concurrently we have implemented the webdriver as threadlocal . This allows the reuse of the driver instance for test cases, once instance of the driver per test class. The thread local copy can then be referenced across any class running within the same JVM and thread.

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