如何进行Mongodb测试?
我们在java中使用Mongodb作为数据库进行存储的时候,怎么样对于进行测试呢?一种可能直接的方式就是在setUp中getDB,然后在tearDown里面dropDatabase。这样的方式相对来说比较慢。一种更好的方式就是使用fake的数据库,比如embedded的Mongodb用于测试。http://xunitpatterns.com/Test%20Double.html
我们这里使用的是https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo
引入依赖
build.gradle
dependencies {
compile "org.mongodb:mongo-java-driver:2.12.2"
testCompile "junit:junit:4.11"
testCompile "de.flapdoodle.embed:de.flapdoodle.embed.mongo:1.46.0"
}
脚手架MongodbBaseTest
编写一个MongoBaseTest,这样所有需要Mongo的测试,可以继承这个类,就可以获取db了。
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();
}
}
编写UserTest
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", "kiwi")
.get();
users.insert(userDocument);
final DBObject userDocumentFromDb = users.findOne(new BasicDBObject("_id", userDocument.get("_id")));
assertThat(userDocumentFromDb.get("name"), is("kiwi"));
}
}
其他:
https://github.com/fakemongo/fongo
Java中的Mongodb单元测试