问题
I would like to run parallel selenium tests (using webriver and the Spring JUnit runner). Webdriver is a spring bean with the custom thread scope. But I get a following warning SimpleThreadScope does not support descruction callbacks
So the browsers are not closed. Any idea how to close them (more precisely call the quit method)?
spring config
<bean id="threadScope" class="org.springframework.context.support.SimpleThreadScope" />
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="thread" value-ref="threadScope" />
</map>
</property>
</bean>
<bean id="webDriver" class="org.openqa.selenium.remote.RemoteWebDriver" scope="thread" destroy-method="quit">
<constructor-arg name="remoteAddress" value="http://localhost:4444/wd/hub" />
<constructor-arg name="desiredCapabilities" ref="browserAgent" />
</bean>
maven config
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>2.12</version>
<configuration>
<includes>
<include>**/*Test.class</include>
</includes>
<reportsDirectory>${basedir}/target/surefire-reports</reportsDirectory>
<parallel>classes</parallel>
<threadCount>2</threadCount>
<perCoreThreadCount>false</perCoreThreadCount>
</configuration>
</plugin>
This post http://www.springbyexample.org/examples/custom-thread-scope-module-code-example.html suggests a custom Thread implementations. But where is an extension point type of Runnable using any JUnit runner?
public class ThreadScopeRunnable implements Runnable {
protected Runnable target = null;
/**
* Constructor
*/
public ThreadScopeRunnable(Runnable target) {
this.target = target;
}
/**
* Runs <code>Runnable</code> target and
* then afterword processes thread scope
* destruction callbacks.
*/
public final void run() {
try {
target.run();
} finally {
ThreadScopeContextHolder.currentThreadScopeAttributes().clear();
}
}
}
回答1:
Here there is a workaround, not perfect solution, because it blocks browsers until the end of all tests.
You have to create a register of thread scope beans which handles their destruction.
public class BeanRegister {
private Set<CustomWebDriver> beans= new HashSet<CustomWebDriver>();
public void register(CustomWebDriver bean) {
beans.add(bean);
}
@PreDestroy
public void clean() {
for (CustomWebDriver bean : beans) {
bean.quit();
}
}
}
Config it as singleton.
<bean class="BeanRegister" />
You have to write a class extending RemoteWebDriver.
public class CustomWebDriver extends RemoteWebDriver {
@Autowired
private BeanRegister beanRegister;
@PreConstruct
public void init() {
beanRegister.register(this);
}
}
That's it.
来源:https://stackoverflow.com/questions/12956776/spring-simplethreadscope-does-not-support-descruction-callbacks