1
我寫了一個小型的研究項目,用mongodb玩一點。我正在使用Spring Data來獲取Mongo Repository。創建RestController並通過Service(另一個類)使用MongoRepository從mongodb中檢索信息並將其呈現給瀏覽器非常簡單。Spring Data MongoDB測試
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
}
現在我決定測試一下我的業務邏輯,並創建了以下類:
@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();
}
}
其中AppConfig.class
看起來:
@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");
}
}
現在我的問題:我真的不想在我存儲數據的同一個數據庫上運行一些測試。此外,我有一個關鍵的方法personRepository.deleteAll()
之後所有的數據將會消失。 我發現嵌入式mongodb作爲解決方案,但是一旦我將它添加到我的pom.xml
中,我看不到已安裝的數據庫了。 所以,問題是是否可以在同一臺機器上同時安裝和嵌入mongodb,如果不是如何在不修改prod數據的情況下測試我的MongoRepository。