Testing the repository in a unit test

We will write a simple unit test to test this repository. The code for the unit test is 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 1: " + person);
}

System.out.println("Person 2: " + personRepository.findByName("name1"));

System.out.println("Person Count: "personRepository.count());
}

}

Some important things to note are as follows:

  • Make sure that MongoDB is running when you 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 that are related to MongoDB.
  • @Autowired PersonMongoDbRepository personRepository: Autowires the MongoDB repository in order for it to be tested.
All the code in the test is very similar to the code written for Spring Data JPAs. This is the beauty of Spring Data: it is one way to connect to a variety of data stores.

We saw that code for interacting with a big database such as MongoDB is made simple, and is very similar to how we talk with 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