Testcontainersの紹介
Testcontainersとは
Section titled “Testcontainersとは”- MySQL等のミドルウェアを利用するアプリケーションのテストコードを書く時に、テストコード内でミドルウェアを起動させることができるライブラリ
- なるべく本番環境に合わせてテストをすることが良いが、テスト前にコンテナを起動しておく必要がある
- テストコード内でミドルウェアを起動させることで、テストコードの実行環境とミドルウェアの実行環境を分離することができる
- Java,Go,.NET,Python,Rust,Haskell,Ruby,Clojure,Elixir,PHPで利用できる
- 今回はGo言語で利用する方法を紹介する
サンプルコード
Section titled “サンプルコード”- 個人的に好きなのでdevcontainerでサンプルを書いた。
$ go versiongo version go1.24.1 linux/arm64
- 実行に必要なものは入れる
go get github.com/go-sql-driver/mysql@latestgo get github.com/testcontainers/testcontainers-go@latestgo get github.com/testcontainers/testcontainers-go/wait@latest
- Testcontainers for Goのインストール(公式ではgo getだが、それだとバージョンが云々と言われたのでこっちを使った)
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)}
- テストコードを実行する
go test ./...
- サンプルコードのためにMySQLのコンテナの準備するの面倒で動かしてないので、サンプルコードで雰囲気を感じてください。
- このままだと普通にpanicします。
Testcontainersを用いてコンテナを利用するGoアプリケーションのテストを改善する Testcontainers Toppage Testcontainers Quickstart