在并行执行中关闭线程之前,spring 或 junit5 hook 中 simplethreadscope 的销毁方法

问题描述

我是 junit5 和 spring 的新手。我正在使用 spring 将 webdriver(selenium) 对象注入页面类。这些页面类被注入到测试中。测试执行完成后,我需要调用 webdriver.quit() 来结束浏览器进程。当 bean 作用域为单例时,我可以使用 destroyMethod 退出()webdriver。

为了与 junit5 并行执行测试,我将 bean 的作用域设置为 SimpleThreadScope,这样每个线程都会注入一个新的驱动程序对象。由于此范围不支持destroyMethod,我被卡住了,无法弄清楚如何在线程级别注入的对象上调用quit()。我发现了一个类似的问题 here 但无法完全遵循解决方案。

我需要帮助

  1. 是否可以使用 destroyMethods 实现自定义范围(线程范围)以及如何在 junit5 中使用它们?
  2. 在并行执行线程即将结束之前,junit5 是否有任何钩子? (我可以在那个钩子中退出驱动程序!)
  3. 我是否根据任何 Spring DI 最佳实践或原则来设计它?请让我知道是否有更好的方法在 spring 和 junit5 中使用破坏钩子注入线程范围对象

这方面的任何例子都会有很大帮助。

下面是我的代码

@Configuration
public class browserBean {
  @Bean(destroyMethod = "quit")
  @Scope(value = "threadScope",proxyMode = ScopedProxyMode.TARGET_CLASS)
  public WebDriver getDriver() {
    String chromeDriverPath = "....../src/test/resources/chromedriver";
    System.setProperty("webdriver.chrome.driver",chromeDriverPath);
    return new ChromeDriver();
  }
}

public class BasePage {
   @Autowired
   public WebDriver browser;
} 

@Component
public class LandingPage extends BasePage {
  public void open(){
    browser.navigate().to("http://google.com");
  }
}

@ExtendWith(SpringExtension.class)
public class SimpleTest extends BaseTest {

    @Autowired
    LandingPage landingPage;

    @Test
    void openSite(){
        landingPage.open();
        Thread t = Thread.currentThread();
        String name = t.getName();
        System.out.println(" *** in SimpleTest " + name + " " + landingPage.driverObject());
    }

    @Test
    void openSite2(){
        landingPage.open();
        Thread t = Thread.currentThread();
        String name = t.getName();
        System.out.println(" *** in SimpleTest1 " + name + " " + landingPage.driverObject());
    }
}  

谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)