2016-09-27 50 views
4

排除Java配置類我和春天有個開機Java的春天開機測試:如何從測試情境

當運行測試,我需要排除一些Java的配置文件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 ...

How我可以做嗎?

+0

請注意,爲了提高開發時間和運行時間的效率,通常最好僅列出要包含*的特定配置類。 – chrylis

回答

2

通常,您將使用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

0

您還可以使用@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