Wednesday, 19 September 2012

Java Mongodb Junit test with Embedded Mongodb

00:53 This is a library for running MongoDB embedded in Java. Normally this is using only for testing purpose and no need to start and stop real mongodb instances.Below example shows how Embedded mongo is working.
Create a Maven project and add below dependency in pom.xml
Test class
package com.vinod.mongo.crud;

import static org.junit.Assert.assertEquals;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.Mongo;
import de.flapdoodle.embedmongo.MongoDBRuntime;
import de.flapdoodle.embedmongo.MongodExecutable;
import de.flapdoodle.embedmongo.MongodProcess;
import de.flapdoodle.embedmongo.config.MongodConfig;
import de.flapdoodle.embedmongo.distribution.Version;
import de.flapdoodle.embedmongo.runtime.Network;

public class EmbededMongoExample {

private static final String DB_NAME = "vinod_test";
private MongodExecutable mongodExe;
private MongodProcess mongod;
private Mongo mongo;
private DB db;
private DBCollection collection;

public void setup() throws Exception {
// Creating Mongodbruntime instance
MongoDBRuntime runtime = MongoDBRuntime.getDefaultInstance();
// Creating MongodbExecutable
mongodExe = runtime.prepare(new MongodConfig(Version.V2_0_1, 12345, Network.localhostIsIPv6()));
// Starting Mongodb
mongod = mongodExe.start();
mongo = new Mongo("localhost", 12345);
// Creating DB
db = mongo.getDB(DB_NAME);
// Creating collection Object and adding values
collection = db.getCollection("EmbeddedCol");

public void teardown() throws Exception {

public void testAddressPersistance() {
BasicDBObject contact = new BasicDBObject();
contact.put("name", "vinod");
contact.put("address", "bangalore");
// Inserting document
DBCursor cursorDoc = collection.find();
BasicDBObject contact1 = new BasicDBObject();
while (cursorDoc.hasNext()) {
contact1 = (BasicDBObject);
assertEquals(contact1.get("name"), "vinod");
Fri Jan  8 00:52:53 [conn2] insert vinod_test.EmbeddedCol 60ms
Fri Jan 8 00:52:53 [conn2] query vinod_test.EmbeddedCol nreturned:1 reslen:81 0ms
{ "_id" : { "$oid" : "568f78e511b1063f2f2a8b28"} , "name" : "vinod" , "address" : "bangalore"}