Spock
Spock extension for Testcontainers library, which allows to use Docker containers inside of Spock tests.
Usage
@Testcontainers
class-annotation
Specifying the @Testcontainers
annotation will instruct Spock to start and stop all testcontainers accordingly. This annotation
can be mixed with Spock's @Shared
annotation to indicate, that containers shouldn't be restarted between tests.
@Testcontainers
class PostgresContainerIT extends Specification {
@Shared
PostgreSQLContainer postgreSQLContainer = new PostgreSQLContainer(SpockTestImages.POSTGRES_TEST_IMAGE)
.withDatabaseName("foo")
.withUsername("foo")
.withPassword("secret")
def "waits until postgres accepts jdbc connections"() {
given: "a jdbc connection"
HikariConfig hikariConfig = new HikariConfig()
hikariConfig.setJdbcUrl(postgreSQLContainer.jdbcUrl)
hikariConfig.setUsername("foo")
hikariConfig.setPassword("secret")
HikariDataSource ds = new HikariDataSource(hikariConfig)
when: "querying the database"
Statement statement = ds.getConnection().createStatement()
statement.execute("SELECT 1")
ResultSet resultSet = statement.getResultSet()
resultSet.next()
then: "result is returned"
int resultSetInt = resultSet.getInt(1)
resultSetInt == 1
cleanup:
ds.close()
}
}
Adding Testcontainers Spock support to your project dependencies
Add the following dependency to your pom.xml
/build.gradle
file:
testImplementation "org.testcontainers:spock:1.20.2"
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>spock</artifactId>
<version>1.20.2</version>
<scope>test</scope>
</dependency>
Attributions
The initial version of this project was heavily inspired by the excellent JUnit5 docker extension by FaustXVI.