本文介绍了Java Spring Boot测试:如何从测试上下文中排除Java配置类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有Spring Boot的Java Web应用程序

I have a Java web app with spring boot

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

When run test I need to exclude some Java config files:

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

Test config (need to include when test run):

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

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

Production config (need to exclude when test run):

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

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

Test class (with explicit config class):

@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 ...

When test is running OTPConfig used, but I need TestOTPConfig...

我该怎么做?

推荐答案

通常,您将使用Spring概要文件来包含或排除Spring Bean,具体取决于哪个概要文件是活动的.根据您的情况,您可以定义生产配置文件,默认情况下可以启用该配置文件.和测试配置文件.在生产配置类中,您将指定生产配置文件:

Typically you would use Spring profiles to either include or exclude Spring beans, depending on which profile is active. In your situation you could define a production profile, which could be enabled by default; and a test profile. In your production config class you would specify the production profile:

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

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

The test config class would specify the test profile:

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

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

Then, in your test class you should be able to say which profiles are active:

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

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

When you run your project in production you would include "production" as a default active profile, by setting an environment variable:

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

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

Of course your production startup script might use something else besides JAVA_OPTS to set the Java environment variables, but somehow you should set spring.profiles.active.

这篇关于Java Spring Boot测试:如何从测试上下文中排除Java配置类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 22:05