I am trying to use EmbeddedMongoDB to work on my tests.
Here are my codes:
@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. I got this code here
@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:
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. Here's my reference for achieving this.