java - Spring Boot - 如何从多模块项目中的姐妹模块启动我的 Spring Boot 应用程序?

标签 java spring spring-boot testing integration-testing

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

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

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

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

<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")
  }
}

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

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

但它仍然不起作用,因为 Spring 没有获取后端/src/main/resources/application.properties

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

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

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

最佳答案

您可以使用 TestPropertySource 覆盖 application.properties 位置像这样:

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

}

关于java - Spring Boot - 如何从多模块项目中的姐妹模块启动我的 Spring Boot 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53692607/

相关文章:

java - 单击java中的DefaultMutableTreeNode时如何检测并显示所需的消息?

Java 迭代器和流

基于Java的配置和扫描

java - Spring /Java 邮件 : The FROM address is being ignored

java - 将自定义 AccessDecisionManager 与 HttpSecurity addFilterBefore 一起使用不起作用

java - Spring Boot Jackson 日期和时间戳格式

在 Linux 上运行的 Java 应用程序在某些网站上出现 SSL 握手错误

java - JOOQ 查询 JOIN ON WITH 子句

java - 使用 JSR303 验证整数

spring-boot - %PARSER_ERROR[wex] 在 Spring Boot 日志记录中