I wrote a small study-project to play a little bit with mongodb. I was using Spring Data to get Mongo Repository. It was quite easy to create RestController and using MongoRepository through Service (another class) retrieve info from mongodb and render it to the browser.
public interface PersonRepository extends MongoRepository<Person, Integer> {
List<Person> findByName(String name);
@Query("{'name':{$regex:?0}}")
List<Person> findByNameLike(String nameLike);
//the rest of methods
}
Now I decided to test my business logic and created the following class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class TestMongo {
private static final Logger LOG = LoggerFactory.getLogger(TestMongo.class);
@Autowired
private PersonRepository personRepository;
@Before
public void setUp() {
Technology technology1 = new Technology("Java-7");
Technology technology2 = new Technology("Java-8");
Technology technology3 = new Technology("Hibernate");
Technology technology4 = new Technology("MyBatis");
Technology technology5 = new Technology("Spring Data");
Project project1 = new Project(1, "POINT", Arrays.asList(technology1, technology3));
Project project2 = new Project(2, "Forecast", Arrays.asList(technology1, technology4));
Project project3 = new Project(3, "CPM", Arrays.asList(technology2, technology5));
Person person1 = new Person(1, "Alex", 27, Arrays.asList(project1, project3));
Person person2 = new Person(2, "Ivan", 26, Arrays.asList(project2, project3));
Person person3 = new Person(3, "Andrii", 31, Arrays.asList(project1));
personRepository.save(Arrays.asList(person1, person2, person3));
}
@Test
public void count() {
List<Person> all = personRepository.findAll();
LOG.info("There are " + all.size() + " person(s) in database");
assertThat(all.size(), equalTo(3));
}
@Test
public void findByName() {
List<Person> personList = personRepository.findByName("Ivan");
LOG.info("*******Find by name********");
LOG.info("personList {}", personList);
LOG.info("***************************");
assertThat(personList, hasSize(1));
}
//another test methods
@After
public void shutDown() {
personRepository.deleteAll();
}
}
where AppConfig.class looks as:
@Configuration
@EnableMongoRepositories
@ComponentScan
public class AppConfig {
@Bean
public MongoClient mongoClient() {
return new MongoClient("localhost", 27017);
}
@Bean
public MongoTemplate mongoTemplate() {
return new MongoTemplate(mongoClient(),"my-mongo");
}
}
And now my problem: I don't actually want to run some tests on the same database where I store my data. Moreover, I have a crucial method personRepository.deleteAll() after which all the data will just vanish.
I found embedded mongodb as a solution but once I add it to my pom.xml I don't see my installed database anymore.
So, the question is whether it's possible to have both installed and embedded mongodb on the same machine and if not how to test my MongoRepository without modifying prod data.