【问题标题】:How to run Spring boot tests concurrently?如何同时运行 Spring Boot 测试?
【发布时间】:2021-06-10 07:39:20
【问题描述】:

我有多个 Spring 测试,一个一个执行,而我想同时运行它们。

代码示例:

@SpringBootTest
@RunWith(Suite.class)
@Suite.SuiteClasses({
     Test1.class,
     Test2.class,
     Test3.class,
     ...
})
public class SuiteStarter { }
    

@RunWith(SpringRunner.class)
@SpringBootTest
public class Test1 {
       @Autowired | @Value fields;

       @org.junit.Test
       public void test1_1() {
            Assertions.assertThat(something1());
        }
       @Test
       public void test1_2() {
            Assertions.assertThat(something2());
        }
}
       ...

有没有类似于用 @Async 注释 Suite 类的东西?我有数百个具有多种方法的测试类,所以最好的解决方案就是更改 SuiteRunner 类,尽可能少做改动,因为我害怕破坏测试。

如果有帮助,我对所有测试都有相同的应用程序上下文。

Running JUnit Test in parallel on Suite Level? 提供的链接已失效且不接受答案。我不需要像这个链接Running junit tests in parallel in a Maven build?中那样的maven并行运行。我也不需要在这里Running Tests in Parallel with Junit 回答,因为它具有实验性功能并且代码看起来也很丑。

【问题讨论】:

标签: spring spring-boot junit spring-test spring-async


【解决方案1】:

所以我发现的最简单和最干净的方法是将此依赖项添加到 Maven

<!-- https://mvnrepository.com/artifact/com.mycila/mycila-junit -->
<dependency>
    <groupId>com.mycila</groupId>
    <artifactId>mycila-junit</artifactId>
    <version>1.4.ga</version>
    <scope>test</scope>
</dependency>

只需更改 SuiteRunner 类

@SpringBootTest
@RunWith(ConcurrentSuiteRunner.class)
@Concurrency(value = 12)
@Suite.SuiteClasses({
...
     

结果

之前:250 秒

之后:60 秒

【讨论】:

    【解决方案2】:

    您可以通过将此配置添加到 maven 来使用新的 spring 5 功能进行并行测试执行:

    <build>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19.1</version>
        <configuration>
            <parallel>methods</parallel>
            <useUnlimitedThreads>true</useUnlimitedThreads>
        </configuration>
    </plugin>
    

    更多细节可以在这里找到: Concurrent Test Execution in Spring 5

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2016-12-22
      • 2022-01-19
      • 2015-10-19
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2020-12-05
      相关资源
      最近更新 更多