【问题标题】:How to use different MongoDB databases in Spring during JUnit tests如何在 JUnit 测试期间在 Spring 中使用不同的 MongoDB 数据库
【发布时间】:2018-03-20 19:00:31
【问题描述】:

我正在使用 JUnit5 为 Spring Boot (2.0) 编写测试,我需要使用不同的数据库来运行单元测试。我怎么知道我的 Spring 应用程序是否由 JUnit 启动?
我打算在AbstractMongoConfiguration 中使用它来在mongoClient() 方法上获取不同的MongoClient 实例。
还是有更好的方法来做到这一点?

【问题讨论】:

  • 您可以使用 application-test.properties 来提供 mongo 相关的属性。

标签: java spring mongodb junit spring-test


【解决方案1】:

您可以拥有特定于配置文件的 mongo 属性,例如用于 test、dev、prod 等的 (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。我们要做的是,我们将所有与 db 相关的配置提取到它们对应的 application.properties 配置文件中。

我的资源文件夹将包含

\资源

-- 应用程序.properties

-- application-dev.properties

-- application-prod.properties

-- 应用程序-qa.properties

-- application-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可以通过使用profiles specific config来控制。

希望这会有所帮助。

【讨论】:

  • OP 询问的是 JUnit 5,而不是 JUnit 4。因此,必须使用 @ExtendWith(SpringExtension.class) 而不是 @RunWith(SpringRunner.class),并且 @Test 注释需要是 org.junit.jupiter.api.Test
  • 感谢您的指出。我只是专注于添加 ActiveProfiles。将根据 Junit 5 进行编辑。
猜你喜欢
  • 2017-09-08
  • 2019-10-26
  • 2015-06-17
  • 1970-01-01
  • 2022-01-13
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多