[英]Spring4 boot unittest @ActiveProfiles causing failed to load applicationContext error
I want to provide different database for running unitTest than using default production database. 我想提供与运行默认生产数据库不同的数据库来运行unitTest。 I thought about using profile to solve this issue.
我考虑过使用配置文件来解决此问题。 This is spring4 boot project, so everything is annotated.
这是spring4引导项目,因此所有内容都带有注释。 This is what I am doing:
这就是我在做什么:
Under src/main/resources, I put application.properties
: 在src / main / resources下,我放置了
application.properties
:
spring.datasource.url=jdbc:postgresql://localhost:5432/services
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.datasource.driver-class-name=org.postgresql.Driver
Under src/test/resources, I put application-test.properties 在src / test / resources下,我放置了application-test.properties
spring.datasource.url=jdbc:postgresql://localhost:5432/services_test
spring.datasource.username=postgres
spring.datasource.password=Hercules1
spring.datasource.driver-class-name=org.postgresql.Driver
Then, I put @ActiveProfiles("test")
before test, now when I run the unit test, I immediately meet this error: 然后,我将
@ActiveProfiles("test")
放在@ActiveProfiles("test")
之前,现在当我运行单元测试时,我立即遇到此错误:
java.lang.IllegalStateException: Failed to load ApplicationContext
java.lang.IllegalStateException:无法加载ApplicationContext
I googled quite a lot and nothing can solve this error. 我用谷歌搜索了很多,没有什么可以解决这个错误。
Can you point out what's wrong with my solution? 您能否指出我的解决方案出了什么问题?
Thanks 谢谢
Just suffixing -test
to application.properties
will not make the properties a candidate for the profile that you activate. 仅将
-test
后缀添加到application.properties
不会使这些属性成为您激活的概要文件的候选项。 You need to do the following: 您需要执行以下操作:
A datasource configuration interface: 数据源配置界面:
public interface DatasourceConfig {
public void setup();
}
Test Datasource configuration: 测试数据源配置:
@Component
@Profile("test")
public class ProductionDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
// Set up your test datasource
}
}
Production datasource configuration: 生产数据源配置:
@Component
@Profile("prod")
public class ProductionDatasourceConfig implements DatasourceConfig {
@Override
public void setup() {
// Set up your prod datasource
}
}
Activate the profile: 激活配置文件:
@ActiveProfiles("test")
Inject the datasource based on environment: 根据环境注入数据源:
@Autowired
DatasourceConfig datasourceConfig;
Beans declared in XML can also be mapped to the profile as below: 以XML声明的Bean也可以如下映射到配置文件:
<beans profile="dev">
<bean id="devDatasourceConfig" class="org.profiles.DevDatasourceConfig" />
</beans>
<beans profile="prod">
<bean id="productionDatasourceConfig" class="org.profiles.ProductionDatasourceConfig" />
</beans>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.