Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a DbUnit alternative that works with MongoDB?

I am developing a project that uses Spring Data and MongoDB to manage the persistence layer. I came across the need to populate some MongoDB collections with data that my integration and unit tests should manipulate. Currently I am using TestNG (and Spring Test) for testing.

Is there a tool like DbUnit that works with MongoDB?

Basically I want that such tool can read documents from an xml file and write such documents in a MongoDB collection.

Or am I missing something obvious, like a best practice for this kind of needs?

like image 557
Marco Ferrari Avatar asked Jan 08 '14 18:01

Marco Ferrari


2 Answers

EmbedMongo is a great tool to use for that. And it integrates with Maven.

EmbedMongo allows you to easily setup an embedded MongoDB instance for test. It has in-built clean up support once tests complete.

See this tutorial. http://blog.yohanliyanage.com/2012/11/integration-testing-mongodb-spring-data/

like image 84
dennisasamoahowusu Avatar answered Oct 29 '22 23:10

dennisasamoahowusu


Here is simple but a little raw util which can set db state to described in json: https://github.com/kirilldev/mongomery

To load database state you need write only two lines of code:

//db here is a com.mongodb.DB instance
MongoDBTester mongoDBTester = new MongoDBTester(db);
mongoDBTester.setDBState("predefinedTestData.json");

To check db state:

mongoDBTester.assertDBStateEquals("expectedTestData.json");

There is two ways to write json files with expected data:

Strict match. This is usual json file wich represents db state. In most cases you don't need more than exact describing of db state after test.

Pattern match. If you want to use random strings in your test or for example your business logic generates random ids for entities you may want a little more than strict match:

{ "Movies": [ { "_id": "$anyObject()", "name": "Titanic", "year": 1997 } ] }

json above says that test expects one document in "Movies" collection that will have name Titanic and a year 1997. Also it must have non null field _id with any object in it.

like image 36
Kirill Reznikov Avatar answered Oct 29 '22 23:10

Kirill Reznikov