一种替代方法是在测试中运行整个spring boot应用程序。在这种情况下,您的spring boot应用程序将被自动发现,嵌入式mongoDB将由Spring Boot下载并启动。
@RunWith(SpringRunner.class)
@SpringBootTest
public class YourSpringBootApplicationTests {
08:12:14.676 INFO EmbeddedMongo:42-注意:noprealloc可能会损害许多应用程序的性能08:12:14.694 INFO EmbeddedMongo:42-2017-12-31T08:12:14.693 + 0200 I CONTROL [initandlisten] MongoDB开始:pid = 2246 port = 52299 08:12:22.005 INFO连接:71-已打开到本地主机的连接[connectionId {localValue:2,serverValue:2}]
在您的示例中,您可以修改代码以在其他端口上启动嵌入式Mongo:
mongo.db.name=person_testDB
mongo.db.url=localhost
mongo.db.port=12345
@EnableMongoRepositories
public class MongoDBConfig {
@Value("${mongo.db.url}")
private String MONGO_DB_URL;
@Value(("${mongo.db.port:27017}"))
private int MONGO_DB_PORT;
@Value("${mongo.db.name}")
private String MONGO_DB_NAME;
@Bean
public MongoTemplate mongoTemplate() {
MongoClient mongoClient = new MongoClient(MONGO_DB_URL, MONGO_DB_PORT);
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);
return mongoTemplate;
}
}
static MongodExecutable mongodExecutable;
@BeforeClass
public static void setup() throws Exception {
MongodStarter starter = MongodStarter.getDefaultInstance();
String bindIp = "localhost";
int port = 12345;
IMongodConfig mongodConfig = new MongodConfigBuilder()
.version(Version.Main.PRODUCTION)
.net(new Net(bindIp, port, Network.localhostIsIPv6()))
.build();
mongodExecutable = null;
try {
mongodExecutable = starter.prepare(mongodConfig);
mongodExecutable.start();
} catch (Exception e){
// log exception here
if (mongodExecutable != null)
mongodExecutable.stop();
}
}
@AfterClass
public static void teardown() throws Exception {
if (mongodExecutable != null)
mongodExecutable.stop();
}
另一种方法是使用MongoRepository和init嵌入式Mongo作为测试@Configuration类的一部分:此处概述:如何配置嵌入式MongDB以在Spring Boot应用程序中进行集成测试?