实际上,您可以使用真正的postgres DB而不是h2来定义集成测试。它会更有用。
主要思想是在集成测试之前运行具有依赖项(postgres DB)的docker实例,并在之后关闭。
下面是一个 maven 的例子:
首先定义规则:
<plugin>
<!-- define Integration tests -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<version>3.0.0-M3</version>
<configuration>
<systemPropertiesFile>${ports.env.file}</systemPropertiesFile>
<includes>
<include>**/*IT.*</include>
</includes>
<additionalClasspathElements>
<additionalClasspathElement>resources</additionalClasspathElement>
</additionalClasspathElements>
<systemPropertiesFile>${it.ports.env.file}</systemPropertiesFile>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
然后需要获取依赖项的可用端口(例如 postgres DB)
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>reserve-network-port</id>
<goals>
<goal>reserve-network-port</goal>
</goals>
<phase>generate-resources</phase>
<configuration>
<portNames>
<portName>DB_PORT</portName>
</portNames>
<outputFile>${it.ports.env.file}</outputFile>
</configuration>
</execution>
</executions>
</plugin>
然后,您应该运行并停止具有依赖关系服务的 Docker 容器(postgres):
<plugin>
<groupId>com.dkanejs.maven.plugins</groupId>
<artifactId>docker-compose-maven-plugin</artifactId>
<version>4.0.0</version>
<configuration>
<envFile>${it.ports.env.file}</envFile>
<envVars>
<COMPOSE_HTTP_TIMEOUT>120</COMPOSE_HTTP_TIMEOUT>
</envVars>
<services>
<service>db-postgres-test</service>
</services>
<composeFiles>
<composeFile>${session.executionRootDirectory}/docker-compose.db-only.yml
</composeFile>
</composeFiles>
<detachedMode>true</detachedMode>
</configuration>
<executions>
<execution>
<id>up</id>
<phase>pre-integration-test</phase>
<goals>
<goal>up</goal>
</goals>
</execution>
<execution>
<id>down</id>
<phase>post-integration-test</phase>
<goals>
<goal>down</goal>
</goals>
<configuration>
<removeVolumes>true</removeVolumes>
<removeOrphans>true</removeOrphans>
</configuration>
</execution>
</executions>
</plugin>
此解决方案可以帮助我更早地解决相同的问题。我希望,它会帮助你。