Testcontainers
website
Repositoryのtest
これのコード片読んで雰囲気が掴めた
code:ts
test("account", async () => {
// コンテナ作成
const container = await new GenericContainer("postgres:latest")..
// クライアント作成
const client = new Client({..});
await client.connect();
await client.query("SELECT 1");
// sqlを取得して、スキーマを作る
const schemaSQL = fs.readFileSync("db/schema.sql", "utf-8");
await client.query(schemaSQL);
// 良い感じにデータを埋めて準備完了
await createAccount(client, {...});
// あとは取得する関数を呼んだりしてテストする
const account = await getAccount(client, { id: "spam" });
expect(account)....
// 後始末など
await client.end();
await container.stop();
}, 30_000);
Dockerコンテナをテスト時に自動起動するツール
対応言語
Java
Go
Node
Python
Rust
例(Java)
code:java
PostgreSQLContainer postgres =
new PostgreSQLContainer("postgres:15");
postgres.start();
用途
DB付き integration test
Kafka / Redis / Elasticsearch テスト
CIでの実環境に近いテスト
メリット
テスト用DBを自動起動
テスト終了で破棄
CIとローカルが一致