使用Golang的模块来使用Testcontainers

Testcontainers with Go

Introduction

介绍

Testcontainers for Go enables developers to run easily tests against containerized dependencies. In our previous articles, you can find an introduction of Integration tests with Testcontainers and explore how to write Functional tests with Testcontainers (in Java).

Testcontainers for Go 让开发人员可以轻松地针对容器化的依赖项运行测试。在我们之前的文章中,你可以找到关于使用 Testcontainers 进行集成测试的介绍如何编写使用 Testcontainers 的功能测试(使用 Java)。

This blog post will deep dive into how to use modules and a common issue for Testcontainers with Golang.

本博客文章将深入介绍如何使用模块以及 Testcontainers 在 Golang 中的一个常见问题。

What we use it for?

我们用它来做什么?

Services often use external dependencies like datastore or queues. It is possible to mock these dependencies but if you want to run for example integration test, it is better to verify against the real dependency (or close enough).

服务通常使用外部依赖项,如数据存储或队列。可以模拟这些依赖项,但如果要运行例如集成测试,则最好针对真实依赖项(或足够接近)进行验证。

Starting a container with the image of the dependency is a convenient way to verify that the application works as expected. With Testcontainers, starting the container is done programmatically so that you can define it as part of your tests. The machine running the tests (developer, CI/CD) requires to have a container runtime interface (e.g. Docker, Podman...)

使用依赖项镜像启动容器是验证应用程序按预期工作的便捷方式。使用 Testcontainers,可以以编程方式启动容器,以便将其定义为测试的一部分。运行测试的机器(开发人员、CI/CD)需要具有容器运行时接口(例如 Docker、Podman...)

Basic implementation

基本实现

Testcontainers for Go is very easy to use, the quick start example is:

Go的Testcontainers非常易于使用,快速入门示例如下:

ctx := context.TODO() req := testcontainers.ContainerRequest{ Image: "redis:latest", ExposedPorts: []string{"6379/tcp"}, WaitingFor: wait.ForLog("Ready to accept connections"), } redisC, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: req, Started: true, }) if err != nil { panic(err) } defer func() { if err := redisC.Terminate(ctx); err != nil { panic(err) } }()

ctx := context.TODO() req := testcontainers.ContainerRequest{ Image: "redis:latest", ExposedPorts: []strin...

开通本站会员,查看完整译文。

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.125.4. UTC+08:00, 2024-06-01 14:05
浙ICP备14020137号-1 $访客地图$