LoginSignup
0
0

【Go言語】Github Actionsを使って自動テストを回す

Posted at

開発をする上でテストを使って検証することは重要です。今回はそのテストをgithub actionsを使って自動で行うことに挑戦したので備忘録を残します。

ファイルを準備する

まずは今回テストする関数を用意します。
今回は簡単な例として、足し算を行うAdd関数を用意しました。

// calc.go

package main

func Add(a, b int) int {
	return a + b
}

次に早速テストを用意します。テストケースは5つほど用意します。

// calc_test.go
package main

import "testing"

// TestAdd はAdd関数のテストを行う
func TestAdd(t *testing.T) {
    testCases := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"Add 1 and 2", 1, 2, 3},
        {"Add -1 and 1", -1, 1, 0},
        {"Add 0 and 0", 0, 0, 0},
        {"Add -5 and -3", -5, -3, -8},
        {"Add 100 and 200", 100, 200, 300},
    }

    for _, tc := range testCases {
        t.Run(tc.name, func(t *testing.T) {
            result := Add(tc.a, tc.b)
            if result != tc.expected {
                t.Errorf("Add(%d, %d) = %d; want %d", tc.a, tc.b, result, tc.expected)
            }
        })
    }
}

まずは念のためローカルで検証を行います。

$ go test ./...
ok      test    0.353s

test.ymlを用意

.github/workflows/test.ymlに以下の内容を記述します。

name: Go

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Set up Go
        uses: actions/setup-go@v2
        with:
          go-version: "1.21"
      - name: Check out code into the Go module directory
        uses: actions/checkout@v2
      - name: Get dependencies
        run: go get -v -t -d ./...
      - name: Test
        run: go test ./...

以上が終わればすべてリモートにpushを行います。

はい。無事にテストが実行されて通過しています

スクリーンショット 2023-12-21 7.50.36.png

CIを失敗させる

次にテストが失敗するパターンを検証します。テストが失敗しててもCIが失敗になっていなかったら問題なのでね。

以下のように変更し、テストが失敗することを検証します。

{"Add 100 and 200", 100, 200, 500},

$ go test ./...
--- FAIL: TestAdd (0.00s)
    --- FAIL: TestAdd/Add_100_and_200 (0.00s)
        calc_test.go:23: Add(100, 200) = 300; want 500
FAIL
FAIL    test    0.363s
FAIL

ではこれをpushします。

そしてGitHub上で確認すると無事CIに失敗していました。よかった!

スクリーンショット 2023-12-21 7.54.52.png

これで自動テストの環境は整備できましたね。これからはテストが自動でできるので便利になりますね。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0