1
votes

I have Spring Boot application:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication()
public class App {

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

build.gradle contains:

testCompile group: "de.flapdoodle.embed", name: "de.flapdoodle.embed.mongo", version: "2.0.0"

and

compile("org.springframework.boot:spring-boot-starter-data-mongodb")

There's controller which uses MongoTemplate

@RestController
@RequestMapping(Constants.MAILBOX_BASE_PATH)
public class MController {

    private static final Logger log = LoggerFactory.getLogger(MailboxController.class);

    private MongoTemplate mongoTemplate;

    @Autowired
    public MController(MongoTemplate mongoTemplate) {
        this.mongoTemplate = mongoTemplate;
    }
}

And test

@RunWith(SpringRunner.class)
@SpringBootTest()
@AutoConfigureMockMvc
public class MontrollerTests { 

    @Autowired
    private MockMvc mvc;

    private MongoTemplate _mongoTemplate;
...
}

My intention is to use embedded MongoDB for the above test. When i run it the following error is popped:

2017-03-05 17:14:51.993 ERROR 27857 --- [ main] o.s.boot.SpringApplication : Application startup failed

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mController' defined...

and at the of the stacktrace there's

java.lang.IllegalStateException: Invalid mongo configuration, either uri or host/port/credentials must be specified

My application properties:

server.port=8090
spring.data.mongodb.uri=mongodb://localhost:27017/test
spring.data.mongodb.port=27017

How to solve this issue? Thanks in advance.

1
You don't need mongo template reference in test. The test will create a embedded mongo template and autowire into controller when you have flap doodle dependency on classpath. Thats pretty much what you need. If that doesn't work trying adding @EmbeddedMongoAutoConfiguration annotation explicity in your test class.s7vr

1 Answers

1
votes

Could you try creating a @Bean for mongoTemplate with EmbeddedMongoFactoryBean class? e.g.:

@Bean
public MongoTemplate mongoTemplate() throws IOException {
    EmbeddedMongoFactoryBean mongo = new EmbeddedMongoFactoryBean();
    mongo.setBindIp("127.0.0.1");
    MongoClient mongoClient = mongo.getObject();
    MongoTemplate mongoTemplate = new MongoTemplate(mongoClient, "some_database");
    return mongoTemplate;
}