[英]Java Spring Boot Test: How to exclude java configuration class from test context
我有一個帶有 Spring Boot 的 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
使用OTPConfig
,但我需要TestOTPConfig
...
我該怎么做?
通常,您將使用 Spring 配置文件來包含或排除 Spring bean,具體取決於哪個配置文件處於活動狀態。 在您的情況下,您可以定義一個生產配置文件,默認情況下可以啟用該配置文件; 和測試配置文件。 在您的生產配置類中,您將指定生產配置文件:
@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 {
....
}
當您在生產中運行您的項目時,您將通過設置環境變量將“生產”作為默認活動配置文件:
JAVA_OPTS="-Dspring.profiles.active=production"
當然,您的生產啟動腳本可能會使用除 JAVA_OPTS 之外的其他東西來設置 Java 環境變量,但您應該以某種方式設置spring.profiles.active
。
您還可以使用@ConditionalOnProperty
如下所示:
@ConditionalOnProperty(value="otpConfig", havingValue="production")
@Configuration
@PropertySource("classpath:otp.properties")
public class OTPConfig { }
和測試:
@ConditionalOnProperty(value="otpConfig", havingValue="test")
@Configuration
@PropertySource("classpath:otp-test.properties")
public class TestOTPConfig { }
然后在你的main/resources/config/application.yml
otpConfig: production
並在您的test/resources/config/application.yml
otpConfig: test
您也可以模擬不需要的配置。 例如:
@MockBean
private AnyConfiguration conf;
把它放到你的測試類中。 這應該有助於避免加載真正的AnyConfiguration
。
此外,為了排除自動配置:
@EnableAutoConfiguration(exclude=CassandraDataAutoConfiguration.class)
public class // ...
我使用的最簡單的方法 -
@ConditionalOnProperty
放在我的主要源代碼中。瞧!
您可以在 Configuration 類中使用@ConditionalOnMissingClass("org.springframework.test.context.junit4.SpringJUnit4ClassRunner")
。 SpringJUnit4ClassRunner
可以被任何只存在於測試環境中的類替換。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.