Testing with a real MongoDB database

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)!

Keeping identical test code in two different classes violates the DRY (Don't Repeat Yourself) principle. If we altered one test class, we should presumably alter the matching test case in the other class. But a new teammate may not be aware of this. It's left as an exercise for the reader to extract an abstract set of test methods to be used by both LiveImageRepositoryTests and EmbeddedImageRepositoryTests.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset