如何 运行 Spring 同时启动测试?

How to run Spring boot tests concurrently?

我有多个 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 class 的东西?我有数百个测试 classes 和多种方法,所以最好的解决方案是只更改 SuiteRunner class,尽可能少的更改,因为我害怕破坏测试。

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

Running JUnit Test in parallel on Suite Level? links provided there are dead and answers were not accepted. I do not need maven parallel run like in this link Running junit tests in parallel in a Maven build?. I also do not need answer in here Running Tests in Parallel with Junit 因为它具有实验性功能,而且代码看起来也很丑。

所以我找到的最简单和最干净的方法是将此依赖项添加到 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 class

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

结果

之前:250 秒

之后:60 秒

您可以将新的 spring 5 功能用于并行测试执行,方法是将此配置添加到 Maven:

<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