Skip to content

Instantly share code, notes, and snippets.

@ftes
Created February 11, 2019 09:06
Show Gist options
  • Save ftes/5d41bee06093508aec52ee7387a8f6ab to your computer and use it in GitHub Desktop.
Save ftes/5d41bee06093508aec52ee7387a8f6ab to your computer and use it in GitHub Desktop.
Spring data mongo + Testcontainers
package de.ftes.examples.spring_data_mongo_testcontainers
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.context.ApplicationContextInitializer
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.core.env.PropertySource
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories
import org.springframework.test.context.ContextConfiguration
import org.testcontainers.containers.GenericContainer
import org.testcontainers.spock.Testcontainers
import spock.lang.Shared
import spock.lang.Specification
@Testcontainers
@EnableAutoConfiguration
@EnableMongoRepositories(basePackages = ["de.ftes.examples.spring_data_mongo_testcontainers"])
@ContextConfiguration(initializers = [Initializer])
class GeneratedRepoTest extends Specification {
static final int MONGO_PORT = 27017
@Shared
static GenericContainer mongo = new GenericContainer("mongo:3.2")
.withExposedPorts(MONGO_PORT)
def setupSpec() {
mongo.start()
}
@Autowired
MyGeneratedRepo repo
def "find uses testcontainer"() {
when:
repo.save(new MyEntity(id: '1'))
then:
repo.findAll().size() == 1
}
static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
void initialize(ConfigurableApplicationContext configurableApplicationContext) {
def props = [
'spring.data.mongodb.uri': "mongodb://${mongo.getContainerIpAddress()}:${mongo.getMappedPort(MONGO_PORT)}/ftes"
]
// In Spring Boot 2, this is a bit easier using `TestPropertyValues.of(...).applyTo(...)`
configurableApplicationContext.getEnvironment().getPropertySources().addFirst(new PropertySource<Map<String, String>>("dynamic props") {
@Override
Object getProperty(String propertyName) {
return props.get(propertyName)
}
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment