Java Spring Boot 测试:如何从测试上下文中排除 Java 配置类

新手上路,请多包涵

我有一个带有 spring 引导的 Java web 应用程序

运行测试时,我需要排除一些 Java 配置文件:

测试配置(测试运行时需要包含):

 @TestConfiguration
@PropertySource("classpath:otp-test.properties")
public class TestOTPConfig { }

生产配置(测试运行时需要排除):

  @Configuration
 @PropertySource("classpath:otp.properties")
 public class OTPConfig { }

测试类(带有显式配置类):

 @RunWith(SpringRunner.class)
@SpringBootTest(classes = TestAMCApplicationConfig.class)
public class AuthUserServiceTest { .... }

测试配置:

 @TestConfiguration
@Import({ TestDataSourceConfig.class, TestMailConfiguration.class, TestOTPConfig.class })
@TestPropertySource("classpath:amc-test.properties")
public class TestAMCApplicationConfig extends AMCApplicationConfig { }

还有类:

 @SpringBootApplication
public class AMCApplication { }

当测试运行时 OTPConfig 使用,但我需要 TestOTPConfig

我该怎么做?

原文由 Sergey 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 964
1 个回答

通常,您会使用 Spring 配置文件来包含或排除 Spring beans,具体取决于哪个配置文件处于活动状态。在您的情况下,您可以定义一个生产配置文件,默认情况下可以启用它;和测试配置文件。在您的生产配置类中,您将指定生产配置文件:

 @Configuration
@PropertySource("classpath:otp.properties")
@Profile({ "production" })
public class OTPConfig {
}

测试配置类将指定测试配置文件:

 @TestConfiguration
@Import({ TestDataSourceConfig.class, TestMailConfiguration.class,    TestOTPConfig.class })
@TestPropertySource("classpath:amc-test.properties")
@Profile({ "test" })
public class TestAMCApplicationConfig extends AMCApplicationConfig {
}

然后,在您的测试类中,您应该能够说出哪些配置文件处于活动状态:

 @RunWith(SpringRunner.class)
@SpringBootTest(classes = TestAMCApplicationConfig.class)
@ActiveProfiles({ "test" })
public class AuthUserServiceTest {
  ....
}

当您在生产环境中运行项目时,您可以通过设置环境变量将“production”作为默认的活动配置文件:

 JAVA_OPTS="-Dspring.profiles.active=production"

当然,您的生产启动脚本可能会使用除 JAVA_OPTS 之外的其他东西来设置 Java 环境变量,但您应该以某种方式设置 spring.profiles.active

原文由 David Miller 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题