SHARE
TWEET

mongoDB testcontainers JUNIT4

Mitis Jan 21st, 2020 (edited) 485 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.demomongo;
  2.  
  3. import org.junit.ClassRule;
  4. import org.junit.Test;
  5. import org.junit.runner.RunWith;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest;
  8. import org.springframework.context.ApplicationContextInitializer;
  9. import org.springframework.context.ConfigurableApplicationContext;
  10. import org.springframework.data.mongodb.core.MongoTemplate;
  11. import org.springframework.test.context.ContextConfiguration;
  12. import org.springframework.test.context.junit4.SpringRunner;
  13. import org.springframework.test.context.support.TestPropertySourceUtils;
  14. import org.testcontainers.containers.GenericContainer;
  15. import static java.lang.String.format;
  16. import static org.assertj.core.api.Assertions.assertThat;
  17. import java.util.List;
  18. import com.example.demomongo.model.Address;
  19. import com.example.demomongo.model.Person;
  20. import com.example.demomongo.dao.PersonRepository;
  21.  
  22.  
  23. @RunWith(SpringRunner.class)
  24. @DataMongoTest
  25. @ContextConfiguration(initializers = TestMongoDockerJUnit4.Initializer.class)  //testcontainers v junit 5
  26. public class TestMongoDockerJUnit4 {
  27.  
  28.     @Autowired
  29.     private MongoTemplate mongoTemplate;
  30.  
  31.     @Autowired
  32.     PersonRepository personRepository;
  33.  
  34.     @ClassRule//container v junit 5
  35.     public static GenericContainer mongoContainer = new GenericContainer("mongo:4.0");
  36.  
  37.     @Test
  38.     public void name() {
  39.         mongoTemplate.insert(new Person("Person First",3, "0905567888","emailfirst@email.cz",1000, new Address("Zlin", "Czech republic")));
  40.         mongoTemplate.insert(new Person("Person Second",3, "0905567888","emailfirst@email.cz",1000, new Address("Zlin", "Czech republic")));
  41.  
  42.         List<Person> all = personRepository.findAll();
  43.  
  44.         assertThat(all.size()).isEqualTo(2);
  45.     }
  46.  
  47.     static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
  48.  
  49.         @Override
  50.         public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
  51.             TestPropertySourceUtils.addInlinedPropertiesToEnvironment(configurableApplicationContext,
  52.                     format("spring.data.mongodb.uri=mongodb://%s:%s",mongoContainer.getContainerIpAddress(), mongoContainer.getMappedPort(27017)));
  53.         }
  54.     }
  55.  
  56. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top