首页 > 解决方案 > Spring Boot - 如何从多模块项目中的姊妹模块启动我的 Spring Boot 应用程序?

问题描述

我有一个包含两个项目的多模块项目:backendclient。后端是一个普通的 Spring Boot Rest API,没什么特别的。客户端模块只是一个使用 Rest API 的 Java 库。

后端也有“war”的包装作为后端,因为它也使用JSP,并且需要部署到servlet容器中。使用@SpringBootTest 仍然可以轻松测试后端。

现在我想在客户端模块中进行一些集成测试,使用后端模块作为沙箱服务器。

要使用我添加的客户端模块中的所有后端类

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-war-plugin</artifactId>
  <configuration>
    <attachClasses>true</attachClasses>
  </configuration>
</plugin>

并将后端配置为带有类的客户端中的测试依赖项

在我的 client/src/test/java 我有一个帮助类启动后端模块

@Configuration  
public class SandboxServer {

  @Bean
  public ConfigurableApplicationContext backend() {
    return 
      new SpringApplicationBuilder(BackendApplication.class)
      .sources(SandboxServerConfig.class)
      .run("spring.profiles.active=sandbox")
  }
}

配置文件“沙盒”用于设置测试数据库等。但我遇到了更多问题。第一个问题是关于文档根目录,所以我对其进行了配置:

public class SandboxServerConfig 
  implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
  @Override
  public void customize(TomcatServletWebServerFactory factory) {
    factory.setDocumentRoot(new File("../backend/src/main/webapp"));
  }
}

但它仍然不起作用,因为 Spring 没有选择 backend/src/main/resources/application.properties

这可能是正确的,因为它不在客户端模块的根类路径中。

所以它并没有真正起作用。我想在集成测试中只启动兄弟模块是不可能的。

如何实现启动兄弟 Spring Boot 模块进行集成测试?像这样的场景的最佳实践是什么?

标签: javaspringspring-boottestingintegration-testing

解决方案


您可以使用TestPropertySourceapplication.properties覆盖该位置,如下所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BlaApplication.class)
@TestPropertySource(locations="/path/to/backend/src/main/resources/application.properties")
public class ExampleApplicationTests {

}

推荐阅读