【问题标题】:How to restart Docker container before each test execution with Maven?如何在每次使用 Maven 执行测试之前重新启动 Docker 容器?
【发布时间】:2020-09-01 18:34:33
【问题描述】:

我想在每次测试执行之前启动一个新的 postgres docker 容器,而不是在运行所有集成测试之前启动一次。 我目前的配置与大多数 Google 结果建议的一样:

     <plugins>
            <plugin>
                <groupId>io.fabric8</groupId>
                <artifactId>docker-maven-plugin</artifactId>
                <version>0.33.0</version>
                <configuration>
                    <imagePullPolicy>IfNotPresent</imagePullPolicy>
                    <images>
                        <image>
                            <alias>it-database</alias>
                            <name>postgres:11.3</name>
                            <run>
                                <namingStrategy>alias</namingStrategy>
                                <ports>
                                    <port>5555:5432</port>
                                </ports>
                                <wait>
                                    <log>(?s)database system is ready to accept connections.*database system is ready to accept connections
                                    </log>
                                    <time>20000</time>
                                </wait>
                            </run>
                        </image>
                    </images>
                </configuration>
                <executions>
                    <execution>
                        <id>docker:start</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>start</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>docker:stop</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>stop</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

【问题讨论】:

    标签: postgresql maven integration-testing maven-failsafe-plugin docker-maven-plugin


    【解决方案1】:

    我强烈建议深入研究Testcontainers,因为 testcontainers 可以在集成测试中完全按照您的喜好进行操作。

    【讨论】:

    • 感谢您的提示。目前我的测试正在使用内存中的 h2 数据库运行。我宁愿不必更改所有测试 - 似乎 Testcontainers 需要额外的代码来启动每个测试。
    • 如果您在 JUnit 5 中使用 JUnit.4 container rule,则正好是一行,您可以通过多种方式实现它......并且 H2 也可以使用 Testcontainers 完成......问题是什么您正在开发哪种应用程序(Spring Boot?)?
    • 是的,Spring Boot,> 30 个微服务,很多很多测试。我可以轻松地将数据库连接字符串更改为 postgres,但不是所有测试
    • 如果您还没有这样做,那么使用 JUnit 5 会更容易。我强烈建议走这条路并更改您的测试以使用 testcontainers 通常使此类测试更容易。问题是您是否需要 postgresql 容器进行集成测试或单元测试,正如您已经提到的使用 H2 ...所以我想这意味着使用 postgresql 的测试并不多...
    • 使用 docker-maven-plugin 的方法已经可以正常工作,只是我无法经常重启 docker 容器。这不需要对单元测试进行任何更改。测试容器是一个有趣的建议,但考虑到我上面的问题,它也有点偏离主题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 2020-05-23
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多