Pregunta

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?

¿Fue útil?

Solución

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/

Otros consejos

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.

You could always use mongodump/mongoimport/mongorestore if you don't mind exec'ing out. Or you could use a file of json documents and use com.mongodb.util.JSON#parse() or jackson to read that json in to DBObjects and write those out to mongo.

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

Here is an example: this approach may be used at the beginning of each integration test session or, if tweaked a bit, even before each integration test. Unfortunately it does not integrate with Maven and assumes Spring to be under the hood.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top