Spring SimpleThreadScope不支持销毁回调

时间:2012-10-18 14:16:24

标签: spring maven webdriver selenium-webdriver

我想运行并行selenium测试(使用webriver和Spring JUnit运行器)。 Webdriver是一个带有自定义线程范围的spring bean。但我收到以下警告SimpleThreadScope does not support descruction callbacks因此浏览器未关闭。知道如何关闭它们(更确切地说是调用退出方法)?

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>

这篇文章http://www.springbyexample.org/examples/custom-thread-scope-module-code-example.html建议自定义Thread实现。但是使用任何JUnit运行器的Runnable的扩展点类型在哪里?

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 个答案:

答案 0 :(得分:1)

这里有一个解决方法,而不是完美的解决方案,因为它会阻止浏览器直到所有测试结束。

你必须创建一个线程范围bean的寄存器来处理它们的破坏。

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();
        }
    }

}

将其配置为单身。

<bean class="BeanRegister" />

您必须编写一个扩展RemoteWebDriver的类。

public class CustomWebDriver extends RemoteWebDriver {

    @Autowired
    private BeanRegister beanRegister;

    @PreConstruct
    public void init() {
        beanRegister.register(this);
    }

}

就是这样。