Testing against an embedded MongoDB instance is quite handy. But there are times when we need to work with a real instance, and for multiple reasons: security settings, a batch of live data, a customized configuration. Whatever the reason, there is no need for that to derail our testing efforts.
We can write another test class, LiveImageRepositoryTests, and make it look like this:
@RunWith(SpringRunner.class) @DataMongoTest(excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class) public class LiveImageRepositoryTests { @Autowired ImageRepository repository; @Autowired MongoOperations operations;
The details for this preceding live test are as follows:
- @RunWith(SpringRunner.class) is our familiar annotation to integrate Spring with JUnit.
- @DataMongoTest (and the other @...Test annotations) lets us exclude explicit autoconfiguration classes. To switch off Flapdoodle, all we need to do is exclude EmbeddedMongoAutoConfiguration
The rest of the code in this class is the same as EmbeddedImageRepositoryTests, so there's no need to show it here. (In fact, it would be quite nice if the exact same tests ran on both embedded as well as a live MongoDB instance.)
Let's run our latest batch of both embedded and live MongoDB tests:
All green (along with the OK icon)!