springboot~基于单元测试的mongodb
添加对应版本的包
testCompile('de.flapdoodle.embed:de.flapdoodle.embed.mongo:1.46.0')
在测试之前,它会根据你的操作系统去下载当前的mongodb,然后在宿主机上去跑它,可能第一次会比较慢 !
添加测试脚手架类
package com.example.springDemo; import com.mongodb.DB; import com.mongodb.MongoClient; import de.flapdoodle.embed.mongo.MongodExecutable; import de.flapdoodle.embed.mongo.MongodProcess; import de.flapdoodle.embed.mongo.MongodStarter; import de.flapdoodle.embed.mongo.config.MongodConfigBuilder; import de.flapdoodle.embed.mongo.config.Net; import de.flapdoodle.embed.mongo.distribution.Version; import de.flapdoodle.embed.process.runtime.Network; import org.junit.After; import org.junit.Before; public class MongodbBaseTest { private static final MongodStarter starter = MongodStarter.getDefaultInstance(); protected MongoClient mongo; protected DB db; private MongodExecutable mongodExecutable; private MongodProcess mongod; @Before public void setUp() throws Exception { mongodExecutable = starter.prepare(new MongodConfigBuilder() .version(Version.Main.PRODUCTION) .net(new Net(12345, Network.localhostIsIPv6())).build()); mongod = mongodExecutable.start(); mongo = new MongoClient("localhost", 12345); db = mongo.getDB("embedded-mongo"); } @After public void tearDown() throws Exception { mongod.stop(); mongodExecutable.stop(); } }
添加测试DEMO类
package com.example.springDemo; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.DBCollection; import com.mongodb.DBObject; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.CoreMatchers.is; public class UserTest extends MongodbBaseTest { private DBCollection users; @Override @Before public void setUp() throws Exception { super.setUp(); users = db.getCollection("users"); } @Test public void should_insert_and_get_user() { final DBObject userDocument = new BasicDBObjectBuilder() .add("name", "lind") .get(); users.insert(userDocument); final DBObject userDocumentFromDb = users.findOne(new BasicDBObject("_id", userDocument.get("_id"))); assertThat(userDocumentFromDb.get("name"), is("lind")); } }
测试如果通过,就出现pass 1的绿色标志
感谢各位阅读!
再次提醒,在测试之前,它会根据你的操作系统去下载当前的mongodb,然后在宿主机上去跑它,可能第一次会比较慢 !