Part 1 – Setting up MongoDB, Spring Data, and JUnit

This is the first in a beginner series on using Spring Data and MongoDB.

This step demonstrates how to pull off a simple MongoDB unit test. (Yes, I know you purists insist on mocking-out your persistence classes and I agree. But we are playing with Mongo templates right now.)

This tutorial assumes you have maven and Mongodb installed already. Other than that, all the files are provided.

We need a simple Mongo document to save in the repo. Let’s start with the ubiquitous Person class.


Now let’s create the coolest part of the whole package. Defining an interface that extends MongoRepository will generate all the CRUD functionality you could ever want. Well, maybe not all.


OK there is one ‘config’ sort of thing. We must define where the database is and that we are using templates. It’s not too bad. However, this is where you’ll find a several styles and methods. I went thru several methods, annotations, templates and all searching for the minimum. For the longest time I was missing @EnableMongoRepositories. Of course, it’s obvious once it’s there. But the error messages I received only talked about not finding the “personRespository” bean.

That’s it for the code. We do need a maven POM and some tests.

And the test class:

Let’s work through some of the code and see where the magic is:

  • Line 12 – @RunWith is some JUnit magic. It clues the system that Spring is going to handle the execution of the test. Now Spring can inject the necessary goodies to enable MongoDB and Spring data templates.
  • Line 13 – @ContextConfiguration tells spring where to look for config information. You can specify XML files, but annotated configuration classes is the way of the future – and much easier to extend. I tried to get rid of this file, but never found a way (Anyone know how?)
  • Line 16-17 – This is our autowired Person Repository. “But that’s only an interface name?” you ask. Yup, Spring Data will generate all the CRUD code we need. No time to go into that now.
  • init() – will clear out our test data and reload it.
  • Line 34 – Finally, we can ask the repository for all the records in the database.

Green Test

There you have it. We’ll use this example to build out a few more tests and examples.