I am learning springboot and have created a simple springboot application. I want it to use the embedded mongoDB when it runs the unit tests and the external mongoDB for the rest of the application. However it uses the external mongoDB for the unit tests instead of the embedded one.
I have following two dependencies in my POM.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>de.flapdoodle.embed</groupId>
<artifactId>de.flapdoodle.embed.mongo</artifactId>
<scope>test</scope>
</dependency>
my properties file has the following:
# MongoDB properties
mongo.db.name=person_testDB
mongo.db.url=localhost
#external Mongo url
spring.data.mongodb.uri=mongodb://localhost:27017/personDB
I have a config file(MongoDBConfig.java) which includes embedded MongoDB configurations:
@EnableMongoRepositories
public class MongoDBConfig {
@Value("${mongo.db.url}")
private String MONGO_DB_URL;
@Value("${mongo.db.name}")
private String MONGO_DB_NAME;
@Bean
public MongoTemplate mongoTemplate() {
MongoClient mongoClient = new MongoClient(MONGO_DB_URL);
MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, MONGO_DB_NAME);
return mongoTemplate;
}
}
Following is my PersonService.java
class:
@Service
public class PersonService {
private static final Logger logger = LoggerFactory.getLogger(PersonService.class);
@Autowired
MongoTemplate mongoTemplate;
public void savePerson(Person person) {
String name = person.getName();
String collectionName = name.substring(0, 1);
mongoTemplate.save(person, collectionName);
}
}
My unit test for the PersonsService class is as follows:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MongoDBConfig.class})
@SpringBootTest(classes = PersonService.class)
@DataMongoTest
public class PersonServiceTest {
@Autowired
PersonService personService;
MongodForTestsFactory factory;
MongoClient mongo;
@Before
public void setup() throws Exception {
factory = MongodForTestsFactory.with(Version.Main.PRODUCTION);
mongo = factory.newMongo();
}
@After
public void teardown() throws Exception {
if (factory != null)
factory.shutdown();
}
@Test
public void testSave(){
Person person = new Person("Bob Smith " , 25);
personService.savePerson(person);
}
}
It creates the collection name and the document name correctly in the external MongoDB which is not what I want. How can I restrict the unitTests to an embedded Mongo?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…