我正在我的 Spring Boot 应用程序中进行集成测试。该应用程序需要使用 Redis。
在开发阶段,我有一个应用程序连接到的本地 Redis 容器。
对于集成测试,我使用testcontainers,并且我还遵循了他们如何使用 Redis 容器的示例。
在某些时候,我了解到只有当开发容器启动并运行时测试才能正确运行。如果它宕机了,那么集成测试就会失败,因为它们无法到达 Redis。
所以集成测试类看起来像这样:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SharkApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestPropertySource(locations = "classpath:application-integrationtests.yml")
@AutoConfigureMockMvc
public class SharkIntegrationTest {
static GenericContainer redis = new GenericContainer("redis:3.0.6")
.withExposedPorts(6379);
@BeforeClass
public static void before(){
redis.start();
}
@AfterClass
public static void after(){
redis.stop();
}
...
Run Code Online (Sandbox Code Playgroud)
运行测试时,我可以在日志中看到以下内容:
14:36:24.372 [main] DEBUG [redis:3.0.6] - Starting container: redis:3.0.6
14:36:24.372 [main] DEBUG [redis:3.0.6] - Trying to start container:
redis:3.0.6
14:36:24.373 [main] DEBUG [redis:3.0.6] - Trying …Run Code Online (Sandbox Code Playgroud) 我的应用程序使用Minio进行 S3 兼容的对象存储,并且我想通过Testcontainers在集成测试中使用 Minio docker 映像。
对于一些非常基本的测试,我使用 docker 映像运行 GenericContainer ,除了和 之外minio/minio没有任何配置。然后我的测试使用 Minio 的Java Client SDK。这些工作正常并且表现得像预期的那样。MINIO_ACCESS_KEYMINIO_SECRET_KEY
但对于其他集成测试,我需要在 Mino 中设置单独的用户。据我所知,用户只能使用Admin API添加到 Minio ,没有 Java 客户端,只有minio/mcdocker 镜像( CLI 在用于服务器的 docker 镜像mc中不可用)。minio/minio
在命令行上,我可以像这样使用 Admin API:
$ docker run --interactive --tty --detach --entrypoint=/bin/sh --name minio_admin minio/mc
Run Code Online (Sandbox Code Playgroud)
保持容器运行有点--interactive --tty困难,这样我以后就可以运行如下命令:
$ docker exec --interactive --tty minio_admin mc admin user add ...
Run Code Online (Sandbox Code Playgroud)
使用 Testcontainers,我尝试这样做:
public void testAdminApi() throws …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用https://www.testcontainers.org/固有的https://github.com/testcontainers/testcontainers-scala,如下所示:
final class MessageSpec extends BddSpec
with ForAllTestContainer
with BeforeAndAfterAll {
override val container = GenericContainer("sweetsoft/sapmock").configure{ c =>
c.addExposedPort(8080)
c.withNetwork(Network.newNetwork())
}
override def beforeAll() {
}
feature("Process incoming messages") {
Run Code Online (Sandbox Code Playgroud)
当我使用命令运行测试时sbt test,出现以下异常:
15:22:23.171 [pool-7-thread-2] ERROR [sweetsoft/sapmock:latest] - Could not start container
org.testcontainers.containers.ContainerLaunchException: Timed out waiting for container port to open (localhost ports: [32775] should be listening)
at org.testcontainers.containers.wait.strategy.HostPortWaitStrategy.waitUntilReady(HostPortWaitStrategy.java:47)
at org.testcontainers.containers.wait.strategy.AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:35)
at org.testcontainers.containers.wait.HostPortWaitStrategy.waitUntilReady(HostPortWaitStrategy.java:23)
at org.testcontainers.containers.wait.strategy.AbstractWaitStrategy.waitUntilReady(AbstractWaitStrategy.java:35)
at org.testcontainers.containers.GenericContainer.waitUntilContainerStarted(GenericContainer.java:582)
Run Code Online (Sandbox Code Playgroud)
该图像是本地图像:
docker images
REPOSITORY TAG IMAGE ID CREATED …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 JUnit 5 模块将可执行初始化 bash 脚本复制init.sh到使用 Testcontainers (1.13.0) 创建的 Localstack Docker 容器中:
@Container
static LocalStackContainer localStack = new LocalStackContainer("0.10.0")
.withServices(S3)
.withCopyFileToContainer(MountableFile.forClasspathResource("init.sh"), "/docker-entrypoint-initaws.d/init.sh");
Run Code Online (Sandbox Code Playgroud)
但在创建的 Docker 容器内,该文件缺少执行权限(使用以下命令查看文件权限进行检查)docker exec -it ID /bin/sh)。
在我的机器上,该文件具有以下权限:
$ ls -al
total 16
drwxr-xr-x 4 xyz staff 128 Apr 16 20:51 .
drwxr-xr-x 4 xyz staff 128 Apr 16 08:43 ..
-rw-r--r-- 1 xyz staff 135 Apr 16 20:14 application.yml
-rwxr-xr-x 1 xyz staff 121 Apr 16 20:51 init.sh
Run Code Online (Sandbox Code Playgroud)
我也尝试使用复制此文件,.withClasspathResourceMapping()但这需要一种仅提供READ_ONLY或的绑定模式 …
使用 Spring 进行集成测试,我可以填充运行脚本的测试数据库,如下所示......
@Test
@Sql({"/db/schema.sql", "/db/accountConfig.sql", "/db/functions/fnSomething.sql"})
public void verifySomething() {
...
}
Run Code Online (Sandbox Code Playgroud)
但是,我想.sql在任何测试运行之前只运行一次所有文件。JUnit 4 是否有方法可以做到这一点?似乎@Sql只针对带有 @Test 注释的方法运行。
我正在使用 Junit 4、Spring Boot、Java 15、Testcontainers。
我尝试过的事情...
@BeforeClass在我的测试类扩展的类上使用,但它似乎在我的测试后运行。ScriptUtils.executeSqlScript,但由于某种原因,测试容器不喜欢这样。这是我的示例代码,适用于@Sql但不适用于ScriptUtils.executeSqlScript.
@ContextConfiguration(initializers = AbstractIntegrationTest.Initializer.class)
public abstract class AbstractIntegrationTest {
@ClassRule
public static MSSQLServerContainer mssqlserver = new MSSQLServerContainer();
public static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
ConfigurableEnvironment environment = configurableApplicationContext.getEnvironment();
Properties props = new Properties();
props.put("spring.datasource.driver-class-name", mssqlserver.getDriverClassName()); …Run Code Online (Sandbox Code Playgroud) 我有以下问题。
为了加速集成测试管道,我想testcontainers使用选项集Quarkus运行。TMPFS这将强制测试容器使用内存文件系统运行数据库。
这可以根据testcontainers这样的网站轻松完成...
要将此选项传递给容器,请将 TC_TMPFS 参数添加到 URL,如下所示: jdbc:tc:postgresql:9.6.8:///databasename?TC_TMPFS=/testtmpfs:rw
看来问题已经解决了。这就是它应该如何工作Spring Boot
然而,Quarkus在他们的文档中,它说了以下内容......
所有基于容器的服务都使用测试容器运行。尽管可以在 application.properties 文件中设置额外的 URL 属性,但不支持特定的 testcontainers 属性,例如 TC_INITSCRIPT、TC_INITFUNCTION、TC_DAEMON、TC_TMPFS。
我的问题是:
如何解决这个问题?如何运行将安装在 TMPFS 上的测试容器?
我有一个集成测试项目,它在 VS 中按预期执行。集成测试使用 MsSql 测试容器(来自https://dotnet.testcontainers.org/)。
我的目标是在 Docker 映像内的 Azure DevOps 管道中运行这些测试,就像我在其他不使用测试容器的项目中成功执行的那样。现在我只是尝试在本地计算机的 docker 映像中运行测试。不幸的是我面临连接问题。
我的环境:
我的代码:
Authentication.Api/MyProject.Authentication.Api/Dockerfile:
##########################################################
# build
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["Authentication.Api/MyProject.Authentication.Api/MyProject.Authentication.Api.csproj", "Authentication.Api/MyProject.Authentication.Api/"]
COPY ["Authentication.Api/MyProject.Authentication.Api.IntegrationTests/MyProject.Authentication.Api.IntegrationTests.csproj", "Authentication.Api/MyProject.Authentication.Api.IntegrationTests/"]
RUN dotnet restore "Authentication.Api/MyProject.Authentication.Api/MyProject.Authentication.Api.csproj"
RUN dotnet restore "Authentication.Api/MyProject.Authentication.Api.IntegrationTests/MyProject.Authentication.Api.IntegrationTests.csproj"
COPY . .
WORKDIR "/src/Authentication.Api/MyProject.Authentication.Api"
RUN dotnet build "MyProject.Authentication.Api.csproj" -c Release -o /app/build
WORKDIR "/src/Authentication.Api/MyProject.Authentication.Api.IntegrationTests"
RUN dotnet build -c Release
##########################################################
# run test projects
FROM build AS tests
WORKDIR /src …Run Code Online (Sandbox Code Playgroud) 尝试测试容器进行集成测试。我正在测试 rest api 端点。这里是技术栈——quarkus、RESTEasy 和 mongodb-client
我能够看到 MongoDB 容器已成功启动但出现异常。异常:“com.mongodb.MongoSocketOpenException:异常打开套接字”
2020-04-26 15:13:18,330 INFO [org.tes.doc.DockerClientProviderStrategy] (main) Loaded org.testcontainers.dockerclient.UnixSocketClientProviderStrategy from ~/.testcontainers.properties, will try it first
2020-04-26 15:13:19,109 INFO [org.tes.doc.UnixSocketClientProviderStrategy] (main) Accessing docker with local Unix socket
2020-04-26 15:13:19,109 INFO [org.tes.doc.DockerClientProviderStrategy] (main) Found Docker environment with local Unix socket (unix:///var/run/docker.sock)
2020-04-26 15:13:19,258 INFO [org.tes.DockerClientFactory] (main) Docker host IP address is localhost
2020-04-26 15:13:19,305 INFO [org.tes.DockerClientFactory] (main) Connected to docker:
Server Version: 19.03.8
API Version: 1.40
Operating System: Docker Desktop
Total Memory: 3940 MB
2020-04-26 …Run Code Online (Sandbox Code Playgroud) 我想使用 JUnit 5 来使用 Testcontainers 和@DataJpaTest(and )。我有使用and注释@SpringBootTest的基本设置,如下所示:@Testcontainers@Container
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import static org.assertj.core.api.Assertions.assertThat;
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@Testcontainers
public class AtleteRepositoryTest {
@Container
private static final PostgreSQLContainer<?> CONTAINER = new PostgreSQLContainer<>("postgres:11");
@DynamicPropertySource
static void registerProperties(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", CONTAINER::getJdbcUrl);
registry.add("spring.datasource.username", CONTAINER::getUsername);
registry.add("spring.datasource.password", CONTAINER::getPassword);
}
@Autowired
private AtleteRepository repository;
@Test
void testSave() {
repository.save(new Atlete("Wout Van Aert", 0, 1, 0)); …Run Code Online (Sandbox Code Playgroud) 我有一个java项目,它使用testcontainers进行集成测试。我想在该阶段实现 gitlab ci 但我遇到了这个错误
\njava.lang.IllegalStateException: Could not find a valid Docker environment. Please see logs and check configuration\nRun Code Online (Sandbox Code Playgroud)\n项目在本地计算机上成功构建,但 gitlap ci docker 无法正确启动
\n这里有一个日志输出
\n\n[0KRunning with gitlab-runner 14.3.0 (b37d3da9)[0;m\n[0K on Backend Docker runner 9L3Zko1w[0;m\nsection_start:1657698628:prepare_executor\n[0K[0K[36;1mPreparing the "docker" executor[0;m[0;m\n[0KUsing Docker executor with image maven:3.6.0-jdk-11-slim ...[0;m\n[0KStarting service docker:dind ...[0;m\n[0KPulling docker image docker:dind ...[0;m\n[0KUsing docker image sha256:232342342342 for docker:dind with digest docker@sha256:2342342342 ...[0;m\n[0KWaiting for services to be up and running...[0;m\n\n[0;33m*** WARNING:[0;m Service runner-23423423-docker-0 probably didn't start properly.\n\nHealth check error:\nservice "runner-234234234-docker-0-wait-for-service" …Run Code Online (Sandbox Code Playgroud) testcontainers ×10
java ×7
docker ×5
junit5 ×2
quarkus ×2
spring-boot ×2
.net ×1
dockerfile ×1
gitlab-ci ×1
junit4 ×1
kotlin ×1
localstack ×1
maven ×1
minio ×1
mongodb ×1
redis ×1
scala ×1
spring ×1
spring-test ×1