Skip to content

Testcontainersの紹介

Author: Murata
  • MySQL等のミドルウェアを利用するアプリケーションのテストコードを書く時に、テストコード内でミドルウェアを起動させることができるライブラリ
  • なるべく本番環境に合わせてテストをすることが良いが、テスト前にコンテナを起動しておく必要がある
  • テストコード内でミドルウェアを起動させることで、テストコードの実行環境とミドルウェアの実行環境を分離することができる
  • Java,Go,.NET,Python,Rust,Haskell,Ruby,Clojure,Elixir,PHPで利用できる
  • 今回はGo言語で利用する方法を紹介する
  • 個人的に好きなのでdevcontainerでサンプルを書いた。
Terminal window
$ go version
go version go1.24.1 linux/arm64
  • 実行に必要なものは入れる
Terminal window
go get github.com/go-sql-driver/mysql@latest
go get github.com/testcontainers/testcontainers-go@latest
go get github.com/testcontainers/testcontainers-go/wait@latest
  • Testcontainers for Goのインストール(公式ではgo getだが、それだとバージョンが云々と言われたのでこっちを使った)
Terminal window
go install github.com/testcontainers/testcontainers-go@latest
package main
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
func TestWithRedis(t *testing.T) {
ctx := context.Background()
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,
})
testcontainers.CleanupContainer(t, redisC)
require.NoError(t, err)
}
  • テストコードを実行する
Terminal window
go test ./...
  • サンプルコードのためにMySQLのコンテナの準備するの面倒で動かしてないので、サンプルコードで雰囲気を感じてください。
  • このままだと普通にpanicします。

Testcontainersを用いてコンテナを利用するGoアプリケーションのテストを改善する Testcontainers Toppage Testcontainers Quickstart