To run all my tests in isolation I would like to drop and recreate a MongoDb collection every time a test method is called, reading the POJO annotations. The problem is that it seems the indexes are created only when MongoTemplate class is instantiated.
This is perfect for the “normal” application, but during the integration testing I would like to have a test like this (maybe too slow for real applications…):
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(loader = AnnotationConfigContextLoader.class, classes = {
ApplicationConfig.class,
MongoConfiguration.class,
TestMongoConfiguration.class})
@ActiveProfiles("test")
public class BookServiceIntegrationTests {
private @Autowired TestHelper testHelper;
@Before
public void startup() {
testHelper.init(Book.class);
}
@After
public void cleanup() {
testHelper.drop(Book.class);
}
//test methods...
}
And this is my pretty straightforward POJO class:
@Document(collection = "books")
public class Book {
@Id
private ObjectId id;
@Indexed(unique = true)
private String isbn;
private String author;
private String title;
private String genre;
private List<String> tags;
private List<Comment> comments;
}
Checking the sources for Spring Data for MongoDB (1.0.1.RELEASE) I saw that the class MongoPersistentEntityIndexCreator is reading the POJO annotations and ensuring the indexes for the colletion. This class is called only inside the MongoTemplate constructor.
Do you think I can find a better way to simulate something like a rollbacked transaction in my tests ?
Thanks,
Carlo
Edit because I can see you want to read the annotations, so what follows might be something you’ve already tried. If you can live with scripting the collection outside of Java, you can try this approach:
Use mongodump and mongorestore using a system runtime exec from Java.
Firstly, take a snapshot of your test collection:
Then in the setup of your JUnit test, restore the collection, dropping the old one first with the –drop option.
This should restore the indexes at the same time.