Reputation: 69920
I need to do several integration tests on a Mongo database using Java, and I was looking for a DbUnit-like solution (DbUnit is for Hibernate) that can populate my database with custom data, and reset the state after each run.
Any tips?
Thanks
Upvotes: 6
Views: 7592
Reputation: 2357
I know this question is old, but maybe my answer will be useful for someone. Here is a simple util that I wrote it recently: https://github.com/kirilldev/mongomery
Very simple to populate db with data from json file:
//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");
It supports placeholders for expected files which can be useful in some situations.
Upvotes: 0
Reputation: 92112
This question has been answered here and permits to start and stop an instance between each test: https://stackoverflow.com/a/9830861/82609
But start/stop between each test seems to slow down integration tests, and thus you'd better start/stop it for the whole test suite: https://stackoverflow.com/a/14171993/82609
Upvotes: 0
Reputation: 45277
To start off, I don't know of any direct equivalent to DBUnit for Mongo. Mongo is still a new product, so you'll probably have to "roll your own" for some of this stuff.
However, there are several features of Mongo that should make this easy:
Based on your dataset there are lots of ways to do this. But the basic tools are there.
So the whole thing should be pretty straightforward. Though you will have to write much of the glue code.
Upvotes: 3
Reputation: 21836
Here's what I do: connect to a known (often shared) mongo instance, but create a new unique database for each test run using a UUID. You don't have to worry about creating collections, as they are created lazily when you store documents in them for the first time. Create any indexes you need in the constructor of the repository or DAO; mongo index creations succeed immediately without doing any work if the index already exists. Obviously, you don't need to worry about schema migrations ;-)
This scheme requires to you to start from an empty datastore, but it's a known state, so it's easy enough to populate in the setup phase of your tests if need be.
When the test is done, delete the entire database in the teardown phase.
Upvotes: 2