【问题标题】:Spring4 boot unittest @ActiveProfiles causing failed to load applicationContext errorSpring引导单元测试@ActiveProfiles导致加载applicationContext错误失败
【发布时间】:2015-04-19 01:17:11
【问题描述】:

我想为运行 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"),现在当我运行单元测试时,我立即遇到了这个错误:

java.lang.IllegalStateException: 无法加载 ApplicationContext

我google了很多,没有什么可以解决这个错误。

你能指出我的解决方案有什么问题吗?

谢谢

【问题讨论】:

  • 如果您所做的只是在 test 和 main 中使用不同的属性,那么不要打扰配置文件。只需将文件命名为application.properties 并将其放入src/test/resources。假设您使用的是 Maven,该目录中的资源将覆盖 src/main/resources 中的资源。
  • 请分享整个错误

标签: java spring spring-boot


【解决方案1】:

仅将 -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>

【讨论】:

  • 很好的答案,非常准确!这是整个互联网上唯一也是最好的答案。我不知道为什么spring doc根本没有提到这一点。再次感谢。
  • 假设您使用的是 Spring Boot,将“-test”后缀添加到属性 就足够了。所以以上都不是必须的。我想这就是为什么它不在文档中...
猜你喜欢
  • 1970-01-01
  • 2017-03-09
  • 1970-01-01
  • 2013-07-07
  • 1970-01-01
  • 2018-06-19
  • 2017-02-18
  • 1970-01-01
  • 2018-03-31
相关资源
最近更新 更多