1. Overview
1.概述
In this tutorial, we’ll explore the Testcontainers Desktop application, a simple yet powerful tool for running Testcontainers. We’ll learn how to use it to configure our Docker environment, manage the container lifecycle, and get insights about our development and testing patterns.
在本教程中,我们将探索 Testcontainers 桌面应用程序,它是运行 Testcontainers 的简单而强大的工具。我们将学习如何使用它来配置 Docker 环境、管理容器生命周期,并深入了解我们的开发和测试模式。
2. Testcontainers Desktop
2.测试容器桌面
Testcontainers Desktop offers a minimal UI designed to simplify the Testcontainer configuration and debugging. We can download Testcontainers Desktop for free from the official website. To start using it, we’ll sign up by creating an account or via a third party like Google, GitHub, or Docker.
Testcontainers Desktop 提供极简用户界面,旨在简化 Testcontainer 配置和调试。我们可以从官方网站免费下载 Testcontainers Desktop。要开始使用它,我们需要创建一个账户或通过第三方(如 Google、GitHub 或 Docker)进行注册。
That’s all! Once we install the application and sign in, we can start using Testcontainers Desktop in our development workflow:
就是这样!安装应用程序并登录后,我们就可以开始在开发工作流程中使用 Testcontainers Desktop 了:
We should see the Testcontainers logo in the taskbar. If we right-click on it, we’ll see some of the key features we’ll be exploring today:
我们应该会在任务栏中看到 Testcontainers 徽标。如果我们右键单击它,就会看到我们今天要探索的一些关键功能:
- Use Testcontainers Cloud
- Freeze containers shutdown
- Define fixed ports
- Interact with the containers
- See Testcontainers dashboard
- Perform advanced customizations
3. Testcontainers Execution Modes
3.测试容器的执行模式
Testcontainers Desktop offers developers two main ways to run tests: locally or in the cloud. Notably, local execution is the default behavior.
Testcontainers Desktop 为开发人员提供了两种主要的测试运行方式:本地或云端。值得注意的是,本地执行是默认行为。
3.1. Local Execution
3.1.本地执行
Local execution leverages our local Docker environment. For instance, let’s run a JUnit test that uses Testcontainers to spin up a MongoDB Docker container:
本地执行利用我们的本地 Docker 环境。例如,让我们运行一个 JUnit 测试,使用 Testcontainers 启动 MongoDB Docker 容器:
@Testcontainers
@SpringBootTest
class DynamicPropertiesLiveTest {
@Container
static MongoDBContainer mongoDBContainer = new MongoDBContainer(DockerImageName.parse("mongo:4.0.10"));
@DynamicPropertySource
static void setProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
}
@Test
void whenRequestingHobbits_thenReturnFrodoAndSam() {
// ...
}
}
If we don’t already have the Docker image locally, we’ll see Docker pulling it in the logs. After that, the MongoDB container starts:
如果本地没有 Docker 镜像,我们就会在日志中看到 Docker 拉取镜像。之后,MongoDB 容器启动:
org.testcontainers.dockerclient.DockerClientProviderStrategy - Found Docker environment with local Npipe socket (npipe:////./pipe/docker_engine)
org.testcontainers.DockerClientFactory - Docker host IP address is localhost
org.testcontainers.DockerClientFactory - Connected to docker:
Server Version: 4.8.3
API Version: 1.41
Operating System: fedora
Total Memory: 7871 MB
org.testcontainers.DockerClientFactory - Checking the system...
org.testcontainers.DockerClientFactory - ✔︎ Docker server version should be at least 1.6.0
tc.mongo:4.0.10 - Pulling docker image: mongo:4.0.10. Please be patient; this may take some time but only needs to be done once.
tc.mongo:4.0.10 - Starting to pull image
tc.mongo:4.0.10 - Pulling image layers: 1 pending, 1 downloaded, 0 extracted, (0 bytes/? MB)
tc.mongo:4.0.10 - Pulling image layers: 0 pending, 2 downloaded, 0 extracted, (0 bytes/0 bytes)
[ ... ]
tc.mongo:4.0.10 - Pull complete. 14 layers, pulled in 17s (downloaded 129 MB at 7 MB/s)
tc.mongo:4.0.10 - Creating container for image: mongo:4.0.10
tc.mongo:4.0.10 - Container mongo:4.0.10 is starting: 3d74c3a...
tc.mongo:4.0.10 - Container mongo:4.0.10 started in PT21.0624015S
Furthermore, we can manually check if the container is created by running the “docker ps” command in the terminal.
此外,我们还可以在终端运行”docker ps“命令,手动检查容器是否已创建。
3.2. Testcontainers Cloud Execution
3.2.测试容器云执行
Testcontainers Cloud provides a scalable platform for running tests in cloud environments. This is ideal if we don’t want to run the containers locally or if we don’t have access to a running Docker environment.
Testcontainers Cloud 为在云环境中运行测试提供了一个可扩展的平台。如果我们不想在本地运行容器,或者无法访问正在运行的 Docker 环境,那么这将是理想之选。
TestContainer Cloud is a paid feature of Testcontainers, but we can use it for free for up to 300 minutes per month.
TestContainer Cloud 是 Testcontainers 的付费功能,但我们可以免费使用,每月最多 300 分钟。
From the small UI, let’s switch to “Run with Testcontainers Cloud”:
从小型用户界面切换到“使用 Testcontainers 云运行”:</em
Let’s re-run the test using this option, and read through the logs again:
让我们使用该选项重新运行测试,并再次阅读日志:
org.testcontainers.dockerclient.DockerClientProviderStrategy - Found Docker environment with Testcontainers Host with tc.host=tcp://127.0.0.1:65497
org.testcontainers.DockerClientFactory - Docker host IP address is 127.0.0.1
org.testcontainers.DockerClientFactory - Connected to docker:
Server Version: 78+testcontainerscloud (via Testcontainers Desktop 1.7.0)
API Version: 1.43
Operating System: Ubuntu 20.04 LTS
Total Memory: 7407 MB
org.testcontainers.DockerClientFactory - Checking the system...
org.testcontainers.DockerClientFactory - ✔︎ Docker server version should be at least 1.6.0
tc.mongo:4.0.10 - Pulling docker image: mongo:4.0.10. Please be patient; this may take some time but only needs to be done once.
tc.mongo:4.0.10 - Starting to pull image
tc.mongo:4.0.10 - Pulling image layers: 0 pending, 0 downloaded, 0 extracted, (0 bytes/0 bytes)
tc.mongo:4.0.10 - Pulling image layers: 12 pending, 1 downloaded, 0 extracted, (0 bytes/? MB)
[ ... ]
As expected, a different environment was used and the Docker images are no longer downloaded locally. Needless to say, if we run the command “docker ps“, we won’t see any container running locally.
不出所料,由于使用了不同的环境,本地不再下载 Docker 映像。不用说,如果我们运行”docker ps“命令,就不会看到任何容器在本地运行。
4. Debugging Testcontainers
4.调试测试容器
Testcontainers Desktop facilitates a smooth debugging experience, through features such as preventing container shutdowns, defining fixed ports, customizing configurations to suit our needs, and directly engaging with containers.
Testcontainers Desktop 通过防止容器关闭、定义固定端口、自定义配置以满足我们的需求以及直接与容器交互等功能,为我们提供了流畅的调试体验。
4.1. Freeze Container Shutdown
4.1.冻结容器关闭
We can use the Desktop application to manually control the container’s lifecycle. For instance, we can use the option “Freeze container shutdown” to allow a running container to keep running even after the test that started it has terminated:
我们可以使用桌面应用程序来手动控制容器的生命周期。例如,我们可以使用选项”冻结容器关闭“来允许正在运行的容器继续运行,即使启动它的测试已经终止:
If we enable this feature and re-run the tests, we’ll receive a notification confirming that the container has been frozen.
如果我们启用此功能并重新运行测试,就会收到通知,确认容器已被冻结。
Next, we’ll identify the port on our local machine that corresponds to the exposed port of the Docker container. MongoDB conventionally operates on port 27017. Let’s open a terminal and run the command “docker ps” to see this mapping:
接下来,我们将确定本地计算机上与 Docker 容器暴露端口相对应的端口。MongoDB 通常在端口 27017 上运行。让我们打开终端并运行命令”docker ps“来查看这一映射:
As we can see, Docker is mapping the container’s port 27017 to port 64215 from our machine. Consequently, we can use this port to connect to the database through our preferred MongoDB client application.
我们可以看到,Docker 正在将容器的端口 27017 映射到我们机器的端口 64215。因此,我们可以使用该端口通过我们喜欢的 MongoDB 客户端应用程序连接数据库。
Studio3T is a graphical user interface for MongoDB, facilitating database management, querying, and visualization. Let’s use it to configure and test the connection to our Mongo Testcontainer:
Studio3T 是 MongoDB 的图形用户界面,便于数据库管理、查询和可视化。让我们用它来配置和测试与 Mongo Testcontainer 的连接:
Our test inserted some records into the “characters” collection from the “test” database. Let’s run a simple query to list all the records from the collection:
我们的测试从”test“数据库中向”characters“集合插入了一些记录。让我们运行一个简单的查询,列出集合中的所有记录:
As we can see, all records are present in the database.
我们可以看到,所有记录都存在于数据库中。
4.2. Define Fixed Ports
4.2.定义固定端口
Normally, Testcontainers starts on random ports. However, if we often need to find the exposed port for debugging purposes, we can define fixed ports instead. To achieve this, we first need to navigate to Services > Open config location. This opens a folder containing configuration examples for a few of the more popular Testconatiners modules:
通常,Testcontainers 会在随机端口上启动。不过,如果我们经常需要找到暴露的端口进行调试,我们可以定义固定端口来代替。要做到这一点,我们首先需要导航到 Services > Open config location。这将打开一个文件夹,其中包含一些常用 Testconatiners 模块的配置示例:
Let’s stick to our use case and inspect the “mongodb.toml.example” file. First, we’ll rename it to “mongodb.toml“, removing the “.example” extension.
让我们根据用例来检查”mongodb.toml.example“文件。首先,我们将其重命名为”mongodb.toml“,去掉”.example“扩展名。
Now, let’s examine the file’s content. The comments explain step by step, how to customize this file to allow Testcontainers Desktop to properly proxy the service’s ports. Let’s focus on the “ports” variable, we can use it to define the mapping between the local port and the container port:
现在,让我们检查一下该文件的内容。注释逐步解释了如何自定义该文件,以便 Testcontainers Desktop 可以正确代理服务端口。让我们关注一下”ports“变量,我们可以用它来定义本地端口和容器端口之间的映射:
# `local-port` configures on which port on your machine the service is exposed.
# `container-port` indicates which port inside the container to proxy.
ports = [
{local-port = 27017, container-port = 27017},
]
As a result, just by renaming the file and enabling this configuration, we’ll be able to connect to the MongoDB database using the fixed port 27017.
因此,只需重命名该文件并启用此配置,我们就能使用固定端口 27017 连接到 MongoDB 数据库。
In other words, we no longer need to manually check the port mapping each time we re-run the test, and we can rely on Mongo’s default port instead.
换句话说,我们不再需要在每次重新运行测试时手动检查端口映射,而是可以依赖 Mongo 的默认端口。
4.3. Interact With the Containers
4.3.与容器互动
Sometimes, even connecting to the database isn’t sufficient, for example when we require more detailed debugging. In this case, we can directly access the Docker container itself. For example, we can open a terminal that is attached to the container and interact with it.
有时,即使连接到数据库也是不够的,例如当我们需要更详细的调试时。在这种情况下,我们可以直接访问 Docker 容器本身。例如,我们可以打开连接到容器的终端并与之交互。
To do this, we navigate to Containers and then we select the container we want to debug. After that, we’ll be prompted with three actions to choose from: “Open terminal“, “Tail logs“, or “Terminate“:
为此,我们要导航到 容器,然后选择要调试的容器。之后,系统会提示我们选择三种操作:”打开终端“、”尾部日志“或”终止“:
The “Open terminal” action allows us to access a terminal attached to the container. For instance, we can use this terminal to start the MongoDB shell and query data without needing to install any MongoDB client application on our local system.
通过”打开终端“操作,我们可以访问连接到容器的终端。例如,我们可以使用该终端启动 MongoDB shell 并查询数据,而无需在本地系统中安装任何 MongoDB 客户端程序。
Let’s start by opening a terminal (Containers > mongo:4.0.10 > Open terminal):
让我们先打开终端(Containers > mongo:4.0.10 > Open terminal):
From this point forward, the instructions depend on the container we use and the use case we want to debug. In our case, let’s execute the following commands:
从这一点出发,指令取决于我们使用的容器和要调试的用例。在我们的例子中,让我们执行以下命令:
- “mongo” – opens the MongoDB shell prompt
- “show dbs” – lists the databases present on the server
- “use test” – switches to the “test” database, the one created by our application
- “db.getCollection(“characters”).find({“race”:”hobbit”})” – queries the “characters” collection and filters by the “race” attribute
As expected, we can see the commands being executed using the MongoDB shell. The last query, db.getCollection(…), retrieves a list of records from the “characters” collection of the “test” database.
不出所料,我们可以看到使用 MongoDB shell 执行的命令。最后一个查询db.getCollection(…)从”test“数据库的”characters“集合中检索记录列表。
5. Testcontainers Dashboard
5.测试容器仪表板
Testcontainers Desktop provides a user-friendly dashboard with a summary of the Testcontainers we used. We can access this webpage by selecting the “Open Dashboard…” option from the menu:
Testcontainers Desktop 提供用户友好的仪表板,其中包含我们使用的 Testcontainers 的摘要。我们可以从菜单中选择”打开仪表板…“选项来访问该网页:
The dashboard offers an overview of the Testcontainers and images used, as well as useful links to resources and account settings. At the bottom of the page, we can see the recent activity and the environment used for execution.
仪表板提供了所用测试容器和图像的概览,以及资源和账户设置的有用链接。在页面底部,我们可以看到最近的活动和用于执行的环境。
This collaborative tool aggregates test data across desktop and CI environments, offering insights into development and testing patterns. Widgets on the dashboard help answer questions about testing consistency, release impact, popular container images, and outdated dependencies.
该协作工具汇总了跨桌面和 CI 环境的测试数据,提供了对开发和测试模式的深入了解。仪表板上的小工具有助于回答有关测试一致性、发布影响、流行容器镜像和过时依赖性的问题。
6. Conclusion
6.结论
In this article, we discovered the diverse features of the Testcontainers Desktop application, which help us run and debug Testcontainers. We explored freezing container shutdowns, employing fixed ports, and accessing a terminal attached to the container. Additionally, we looked at the Testcontainers Dashboard, a tool that enhances visibility and insights into testing activities.
在本文中,我们发现了 Testcontainers 桌面应用程序的各种功能,它们可以帮助我们运行和调试 Testcontainers。我们探索了冻结容器关闭、使用固定端口和访问连接到容器的终端。此外,我们还了解了 Testcontainers 控制面板,这是一种可提高测试活动可见性和洞察力的工具。
As always, the code examples used in this article are available over on GitHub.
与往常一样,本文中使用的代码示例可在 GitHub 上获取。