You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spock测试中如何获取TestContainers创建的默认Java容器的名称或ID

解决方案

场景1:Java应用本身也作为Testcontainers管理的容器运行

如果你的Java服务是通过@Testcontainers注解直接管理的容器实例,可直接调用容器实例的内置方法获取ID和名称:

// 你定义Java应用容器的代码示例
@Shared
@ServiceConnection
SpringBootContainer appContainer = new SpringBootContainer("my-java-app:latest")

// 直接调用方法获取信息
String containerId = appContainer.getContainerId()
String containerName = appContainer.getContainerInfo().getName()

拿到信息后你可以通过环境变量的形式注入到自定义的selenium容器中,供Python脚本直接读取:

@Shared
protected GenericContainer seleniumStandalone =
        new GenericContainer<>("selenium/standalone-chrome:latest")
                .withExposedPorts(4444)
                // 注入Java应用容器的访问地址
                .withEnv("JAVA_APP_HOST", appContainer.getContainerIpAddress())
                .withEnv("JAVA_APP_PORT", appContainer.getMappedPort(8080).toString())
                .withCreateContainerCmdModifier({ cmd -> cmd.withName('dockerized-chrome') })
                .withCopyFileToContainer(
                        MountableFile.forClasspathResource("install_python.sh", 0744),"/install_python.sh")
                .withCopyFileToContainer(
                        MountableFile.forClasspathResource("test.py", 0744),"/test.py")

场景2:Java应用通过Docker Compose模块启动

如果你是用Testcontainers的DockerComposeContainer管理整套服务,可通过服务名称获取对应的容器实例:

@Shared
DockerComposeContainer<?> composeContainer = new DockerComposeContainer<>(new File("docker-compose.yml"))
        .withExposedService("app-service", 8080)

// 获取Java服务容器
GenericContainer<?> appContainer = (GenericContainer<?>) composeContainer.getContainerByServiceName("app-service").get()
String containerId = appContainer.getContainerId()
String containerName = appContainer.getContainerInfo().getName()

场景3:Java应用运行在宿主机测试进程中(常规测试场景)

这种情况无需获取任何容器信息,Testcontainers内置了特殊域名host.testcontainers.internal,可以直接从任意Testcontainers管理的容器中访问宿主机的端口,你直接在Python脚本中请求该域名+Java应用启动的端口即可:

# test.py 示例代码
import requests
response = requests.get("http://host.testcontainers.internal:8080/your/api/endpoint")

问题参考示意图:
问题示意图

内容的提问来源于stack exchange,提问作者maciejka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 18:24:10