1

我有一個春天啓動的項目,1.5.4版配置類,用MongoDB的配置類:春季啓動1.5.4:排除單元測試

@Configuration 
public class MongoConfig { 

@Value("${spring.data.mongo.client.uri:mongodb://localhost:27017/database}") 
private String mongoURI; 

@Bean 
public MongoDbFactory mongoFactory() throws UnknownHostException{ 
    return new SimpleMongoDbFactory(new MongoClientURI(mongoURI)); 
} 

@Bean 
public MongoTemplate mongoTemplate() throws UnknownHostException, MongoException{ 
    return new MongoTemplate(mongoFactory()); 
} 
} 

在我的集成測試,我想使用嵌入式蒙戈https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo)。

的問題是,嵌入式蒙戈的initialitation前MongoDB的配置類開始,並嘗試連接到數據庫,所以我的測試失敗。如果我刪除了MongoConfig類,所有測試都很好。

我怎麼能排除它只是在我的測試執行?

+0

我知道這是不是你的問題是什麼,但看看testContainers:https://www.testcontainers.org/這是解決方案,我用我的測試(主要是集成測試),一個小教程在這裏:https://areguig.github.io/test-springboot-apps-using-testContainers-and-spock/ –

回答

1

請在這裏參考的答案。它有兩種排除配置的方法。

Spring boot: apply @Configuration to certain package only

更新1:

或者,我能想到的最有效的方法是使用Spring配置文件並加載配置文件進行測試

定義您TestConfiguration類將它導入您的測試課程。

@RunWith(SpringRunner.class) 
@SpringBootTest 
@Import(MyTestConfiguration.class) 
public class MyTests { 

    @Test 
    public void exampleTest() { 
     ... 
    } 

} 

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-testing.html#boot-features-testing-spring-boot-applications-detecting-config

更新2: 對於EmbeddedMongoAutoConfiguration請在這裏參考了詳細的解答。

How do you configure Embedded MongDB for integration testing in a Spring Boot application?

+0

我不想改變我的主要應用程序類的單元測試。 – sintetico82

+0

@Import(MyTestsConfiguration.class)是很好的解決方案,但我發現了一個系統,只是避免負載無用類爲我的測試。 – sintetico82

+0

的proble是,我不知道該怎麼做我的* MyTestsConfiguration.class *,becouse我想激活* EmbeddedMongoAutoConfiguration.class * – sintetico82

0

我這個配置解決它在我的測試類:

@RunWith(SpringRunner.class) 
@ComponentScan({"it.app.server.dal","it.app.server.listener"}) 
@DataMongoTest() //mongoDB 
public class ListenerTests { 
    ... 
} 

註解@DataMongoTest()加載我Embbedded的MongoDB,並與@ComponentScan我可以只加載服務和存儲庫,我需要在我的測試。

+0

如果我想測試訪問MongoDB的一個控制器此解決方案不起作用。 – sintetico82