运行 集成测试前的主springboot应用

Run main springboot application before integration tests

如何在 Maven 集成测试之前 运行 主应用程序? 现在我有一个非常糟糕的解决方案。使用注释代码进行的测试可以正常工作,但我需要良好的实践方式。

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
@Category(Integration.class)
@ActiveProfiles("test")
@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
public class MyTestClass {

@BeforeClass
public static void setUp(){

    /*SpringApplication.run(MyApplication.class).close();

    System.setProperty("spring.profiles.active", "test");
    MyApplication.main(new String[0]);*/
}

我想要 运行 由 maven 进行带有参数的测试:

clean integration-test -Dgroups=xxx.annotation.type.Integration -Drun.jvmArguments=-Dspring.profiles.active=test

但它不起作用。我如何更正此 Maven 命令行?

您可以使用 spring-boot-maven-plugin 并将其绑定到 Maven 中的预集成测试阶段,如下所示:

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>2.0.4.RELEASE</version>
        <executions>
          <execution>
            <id>pre-integration-test</id>
            <goals>
              <goal>start</goal>
            </goals>
          </execution>
          <execution>
            <id>post-integration-test</id>
            <goals>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

要运行您的应用程序在集成测试的特定配置文件上,您需要使用 @SpringBootTest@ActiveProfiles 注释测试 class 和 @ActiveProfiles 参数如下:

@SpringBootTest(classes = {MyApplication.class},  webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")

当您使用 @ActiveProfiles 上指定的配置文件提供 webEnvironment = WebEnvironment.RANDOM_PORT 时,您在 classes = {MyApplication.class} 中定义的应用程序将在随机端口上启动。如果您希望它在定义的端口上为 运行,则使用 WebEnvironment.DEFINED_PORT。如果您需要获取端口(随机端口),您可以将其值自动连接到本地字段以进行测试,如下所示:

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
class TestClass {
    @LocalServerPort
    private int port;
    @Test public void someTest() {}
}