How do I do mongodb testing?
when we use MongoDB as a database for storage in Java, what about testing? One possible direct way is to GETDB in Setup and then dropdatabase inside the teardown. This approach is relatively slow. A better way is to use fake databases, such as embedded's MongoDB, for testing. http://xunitpatterns.com/Test%20Double.html
We're using Https://github.com/flapdoodle-oss/de.flapdoodle.embed.mongo here.
Introducing Dependencies
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"
}
Scaffolding Mongodbbasetest
Write a mongobasetest so that all the tests that need to be MONGO can inherit this class and get the 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 ();
}
}
Writing 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"));
}
}
Other:
Https://github.com/fakemongo/fongo