How to use Embedded MongoDB on Spring Boot Integration tests

admin

Administrator
Staff member
I am trying to use EmbeddedMongoDB to work on my tests.

Here are my codes:

Code:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {MyWebServiceApplication.class, TestMongoConfig.class})
public class MyWebServiceApplicationTests {

@Autowired 
InfoRepository repository;

@Before
public void setUp() {

}

@Test
public void setsIdOnSave() {
    Info dave = repository.findInfoByMobileNumber(917900);
    assertThat(dave.getCarrier(), is(notNullValue()));
    }
}

If I remove TestMongoConfig.class, the test works but it is connecting to the live DB.

Here's the TestMongoConfig class. <a href="https://stackoverflow.com/questions...egration-testing-in-a-spring-boot-ap/35204466">I got this code here</a>

Code:
@Configuration
public class TestMongoConfig {

@Autowired
private MongoProperties properties;

@Autowired(required = false)
private MongoClientOptions options;

@Bean(destroyMethod = "close")
public Mongo mongo(MongodProcess mongodProcess) throws IOException {
    Net net = mongodProcess.getConfig().net();
    properties.setHost(net.getServerAddress().getHostName());
    properties.setPort(net.getPort());
    return properties.createMongoClient(this.options);
}

@Bean(destroyMethod = "stop")
public MongodProcess mongodProcess(MongodExecutable mongodExecutable) throws IOException {
    return mongodExecutable.start();
}

@Bean(destroyMethod = "stop")
public MongodExecutable mongodExecutable(MongodStarter mongodStarter, IMongodConfig iMongodConfig) throws IOException {
    return mongodStarter.prepare(iMongodConfig);
}

@Bean
public IMongodConfig mongodConfig() throws IOException {
    return new MongodConfigBuilder().version(Version.Main.PRODUCTION).build();
}

@Bean
public MongodStarter mongodStarter() {
    return MongodStarter.getDefaultInstance();
}

}

Now, I am getting this error:

Code:
Could not autowire field: private org.springframework.boot.autoconfigure.mongo.MongoProperties com.example.TestMongoConfig.properties

Please note that my application is connecting to two different MongoDB instances. My configuration for the "live" connection isn't using Autoconfiguration and it has its own beans. <a href="https://falkenfighter.wordpress.com...abases-with-spring-boot-mongodb-repositories/" rel="nofollow noreferrer">Here's my reference for achieving this.</a>