Is there an alternative to DbUnit that works with MongoDB?

I am developing a project that uses Spring Data and MongoDB to control the persistence level. I was faced with the need to populate some MongoDB collections with data that my integration and unit tests should perform. I am currently using TestNG (and Spring Test) for testing.

Is there a tool like DbUnit that works with MongoDB?

Basically, I want such a tool to be able to read documents from an XML file and write such documents to the MongoDB collection.

Or am I missing something obvious as best practice for this kind of need?

+6
source share
4 answers

EmbedMongo is a great tool for this. And it integrates with Maven.

EmbedMongo makes it easy to set up a built-in instance of MongoDB for testing. After completing the tests, it has built-in cleaning support.

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

+3
source

Here is a simple but slightly raw usage that can set the db state in json: https://github.com/kirilldev/mongomery

To load the state of a database, you only need to write two lines of code:

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

To check the status of db:

 mongoDBTester.assertDBStateEquals("expectedTestData.json"); 

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

Strict coincidence. This is a regular json file representing the state of db. In most cases, you do not need a more accurate description of the state of db after the test.

Matching pattern. If you want to use random strings in your test or, for example, your business logic generates random identifiers for objects, you can do a little more than strict matching:

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

json above says the test expects that one document in the Movies collection will have the name Titanic and year 1997. It should also have a non-zero _id field with any object in it.

+1
source

You can always use mongodump / mongoimport / mongorestore if you don't mind. Or you can use a json document file and use com.mongod.util.JSON # parse () or jackson to read json in in DBObjects and write them to mongo.

0
source

In one of my projects (in which Spring was available), I ended up using ApplicationListener , which listens for ContextRefreshedEvent .

Here is an example: this approach can be used at the beginning of each integration session or, if it is slightly modified, even before each integration test. Unfortunately, it does not integrate with Maven and assumes that Spring is under the hood.

0
source

All Articles