如何在JUnit测试期间在Spring中使用不同的MongoDB数据库

时间:2018-03-20 19:00:31

标签: java spring mongodb junit spring-test

我正在使用JUnit5为Spring Boot(2.0)编写测试,我需要使用不同的DB来运行单元测试。如果我的Spring应用程序是由JUnit启动的,我怎么知道呢? 我打算在AbstractMongoConfiguration中使用此功能,以便在MongoClient方法上获取不同的mongoClient()个实例。
或者有更好的方法吗?

1 个答案:

答案 0 :(得分:2)

您可以为test,dev,prod等设置特定于配置文件的mongo属性,例如(URI)。

示例测试类(针对Junit5更新)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest
@ActiveProfiles(profiles = {"test"})
public class SampleTest {
    @Autowired
    MongoTemplate mongoTemplate;


    //.....  Some Test methods goes here .... 

}

在上述情况下,我们提供名为 test 的配置文件作为ActiveProfiles。因此,默认情况下,将从类路径(资源)中选择两个属性,其中一个属性为application.properties,其他属性为application-test.properties。我们将要做的是,我们将所有与数据库相关的配置提取到application.properties的配置文件对应部分。

我的资源文件夹将包含

\资源

- application.properties

- application-dev.properties

- application-prod.properties

- application-qa.properties

- application-test.properties

applicaion-test.properties

spring.data.mongodb.uri=mongodb://<test db ip config goes here>/test_app_db

<强> application-dev.properties

spring.data.mongodb.uri=mongodb://<dev ip>/app_db

依此类推,可以使用特定于配置文件的配置来控制不同的mongo bean。

希望这有帮助。