Unit test

We will write a simple unit test to test this repository. The code for the unit test is shown as follows:

    @DataMongoTest
@RunWith(SpringRunner.class)
public class PersonMongoDbRepositoryTest {
@Autowired
PersonMongoDbRepository personRepository;
@Test
public void simpleTest(){
personRepository.deleteAll();
personRepository.save(new Person( "name1"));
personRepository.save(new Person( "name2"));
for (Person person : personRepository.findAll()) {
System.out.println(person);
}
System.out.println(personRepository.findByName("name1"));
System.out.println(personRepository.count());
}
}

Some important things to note are as follows:

  • Make sure that MongoDB is running when your run the test.
  • @DataMongoTest: The DataMongoTest annotation is used in combination with SpringRunner for a typical MongoDB unit test. This disables auto-configuration for everything except things related to MongoDB.
  • @Autowired PersonMongoDbRepository personRepository: Autowires the MongoDB repository to be tested.

An important thing to note is that all the code in the test is very similar to the code written for Spring Data JPA. This example show how simple Spring Data makes it to connect to different kinds of data stores. The code to interact with a nonrelational Big Data data store is similar to the code that talks to a relational database. That's the magic of Spring Data.

..................Content has been hidden....................

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