在集成测试之前运行主springboot应用程序

时间:2018-08-30 10:57:48

标签: java spring spring-boot integration-testing

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

ALLOWED_HOSTS

我想通过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命令行?

2 个答案:

答案 0 :(得分:2)

要在特定配置文件上运行应用程序以进行集成测试,您需要使用@SpringBootTest@ActiveProfiles为测试类添加以下参数:

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

使用classes = {MyApplication.class}上指定的配置文件提供webEnvironment = WebEnvironment.RANDOM_PORT时,将在随机端口上启动您在@ActiveProfiles中定义的应用程序。如果您希望它在定义的端口上运行,请使用WebEnvironment.DEFINED_PORT

答案 1 :(得分:0)

您可以使用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>

相关问题