簡體   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