繁体   English   中英

Spring4启动单元测试@ActiveProfiles导致无法加载applicationContext错误

[英]Spring4 boot unittest @ActiveProfiles causing failed to load applicationContext error

我想提供与运行默认生产数据库不同的数据库来运行unitTest。 我考虑过使用配置文件来解决此问题。 这是spring4引导项目,因此所有内容都带有注释。 这就是我在做什么:

在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

在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

然后,我将@ActiveProfiles("test")放在@ActiveProfiles("test")之前,现在当我运行单元测试时,我立即遇到此错误:

java.lang.IllegalStateException:无法加载ApplicationContext

我用谷歌搜索了很多,没有什么可以解决这个错误。

您能否指出我的解决方案出了什么问题?

谢谢

仅将-test后缀添加到application.properties不会使这些属性成为您激活的概要文件的候选项。 您需要执行以下操作:

数据源配置界面:

public interface DatasourceConfig {
    public void setup();
}

测试数据源配置:

@Component
@Profile("test")
public class ProductionDatasourceConfig implements DatasourceConfig {
    @Override
    public void setup() {
        // Set up your test datasource
    }
}

生产数据源配置:

@Component
@Profile("prod")
public class ProductionDatasourceConfig implements DatasourceConfig {
    @Override
    public void setup() {
        // Set up your prod datasource
    }
}

激活配置文件:

@ActiveProfiles("test")

根据环境注入数据源:

@Autowired
DatasourceConfig datasourceConfig;

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM