如何在 spring 引导中使用 testcontainers 正确 运行 spock 测试

How to properly run spock test using testcontainers in spring boot

我有一个 spring 启动应用程序,测试使用 spocktestcontainers (mysql) 编写。我所做的工作正常,但感觉不对(f.e。因为每次测试迭代都会使用 @sql,所以我必须在我的 [=62= 中使用 INSERT IGNORE ... ] 脚本。我对静态和非静态 mysql 容器的技巧也不满意。 对于测试容器(实际上是 spock),我是一个完全的初学者,所以如果有人能告诉我如何使用 spock@sql、数据源和 testcontainers 让它变得更好,我将不胜感激.

@SpringBootTest
@ContextConfiguration(initializers = Initializer.class)
@Testcontainers
class GeneratorTest extends Specification {

    public static MySQLContainer staticMySQLContainer = new MySQLContainer()
            .withDatabaseName("test")
            .withUsername("test")
            .withPassword("test")

    @Shared
    public MySQLContainer mySQLContainer = mySQLContainer;

    static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

        @Override
        void initialize(@NotNull ConfigurableApplicationContext configurableApplicationContext) {
            TestPropertyValues values = TestPropertyValues.of(
                    "spring.datasource.url=" + staticMySQLContainer.getJdbcUrl(),
                    "spring.datasource.password=" + staticMySQLContainer.getPassword(),
                    "spring.datasource.username=" + staticMySQLContainer.getUsername()
            )
            values.applyTo(configurableApplicationContext)
        }
    }

    @Autowired
    private CarService carService
    @Autowired
    private BikeRepository bikeRepository

    @Sql("/testdata/insert_into_cars.sql")
    def "validate number of doors"(int carId, int expectedNrOfDoors) {
        given:
        Car car = carService.getById(carId)

        expect:
        car.getNrOfDoors() == expectedNrOfDoors

        where:
        carId || expectedNrOfDoors
        1     || 3
        2     || 3
        3     || 5
    }
}

已更新(使用基于 jdbc 的容器)
当谈到 JDBC-based containers 时,我不确定我是否设置正确。我在 test/resources 目录中创建了 application-test.properties。我放在那里:

spring.datasource.url=jdbc:tc:mysql:8.0.12://localhost:3306/shop?createDatabaseIfNotExist=true&serverTimezone=UTC
spring.datasource.username=test
spring.datasource.password=test
spring.datasource.driver-class-name=org.testcontainers.jdbc.ContainerDatabaseDriver

我的测试 class 看起来像:

@SpringBootTest
@Testcontainers
@TestPropertySource(locations="classpath:application-test.properties")
class GeneratorTest extends Specification {

    @Autowired
    private CarService carService

    <skipped for brevity>

当我尝试 运行 测试时 class 我不断得到:

    2018-11-20 19:10:25.409 2612@DESKTOP-MLK30PF  INFO --- [main]  [mysql:8.0.12].waitUntilContainerStarted : Waiting for database connection to become available at jdbc:mysql://192.168.99.100:32770/shop using query 'SELECT 1' (JdbcDatabaseContainer.java:128) 
2018-11-20 19:12:25.420 2612@DESKTOP-MLK30PF ERROR --- [main]  [mysql:8.0.12].tryStart : Could not start container (GenericContainer.java:297) 
org.rnorth.ducttape.TimeoutException: org.rnorth.ducttape.TimeoutException: java.util.concurrent.TimeoutException
    at org.rnorth.ducttape.unreliables.Unreliables.retryUntilSuccess(Unreliables.java:53)
    at org.testcontainers.containers.JdbcDatabaseContainer.waitUntilContainerStarted(JdbcDatabaseContainer.java:129)
    at org.testcontainers.containers.GenericContainer.tryStart(GenericContainer.java:292)

接着是

2018-11-20 19:12:25.486 2612@DESKTOP-MLK30PF  INFO --- [tc-okhttp-stream-242833949]  [mysql:8.0.12].accept : STDERR: 2018-11-20T18:10:44.918132Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.12'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server - GPL. (Slf4jLogConsumer.java:32) 
2018-11-20 19:12:25.487 2612@DESKTOP-MLK30PF  INFO --- [main]  [mysql:8.0.12].tryStart : Creating container for image: mysql:8.0.12 (GenericContainer.java:253) 
2018-11-20 19:12:25.609 2612@DESKTOP-MLK30PF  INFO --- [main]  [mysql:8.0.12].tryStart : Starting container with ID: de75c9dafed8032b84cb827bf43a29c1964bfe4e168422272c9310a4803fd856 (GenericContainer.java:266) 
2018-11-20 19:12:25.896 2612@DESKTOP-MLK30PF  INFO --- [main]  [mysql:8.0.12].tryStart : Container mysql:8.0.12 is starting: de75c9dafed8032b84cb827bf43a29c1964bfe4e168422272c9310a4803fd856 (GenericContainer.java:273) 
2018-11-20 19:12:25.901 2612@DESKTOP-MLK30PF  INFO --- [main]  [mysql:8.0.12].waitUntilContainerStarted : Waiting for database connection to become available at jdbc:mysql://192.168.99.100:32772/shop using query 'SELECT 1' (JdbcDatabaseContainer.java:128) 

对于 mysql 版本 8 的问题请查看 here

更新(已解决):
正如@bsideup 指出的那样,基于 jdbc 的容器是该用例的最佳解决方案。正如我在上面描述的那样,它工作得很好,但我不得不将 mysql 版本从 8 更改为更低版本。

你试过了吗JDBC-based containers

你可以做到

def setupSpec(){ //or use setup(){ if not a @Shared Container
System.getProperties()
                    .putAll([
                            "spring.datasource.url"     : mySQLContainer...,
                            "spring.datasource.username": mySQLContainer...,
                            "spring.datasource.password": mySQLContainer...
                    ])
}

然后你可以去掉 staticMySQLContainer

还有初始化程序