Goのテストでset-upとtear-down


概要

go 1.14 からであれば「TestMain」を使うことができる

サンプル


package main

import (
    "log"
    "os"
    "testing"
)

func TestMain(m *testing.M) {
    log.Println("Do stuff BEFORE the tests!")
    exitVal := m.Run()
    log.Println("Do stuff AFTER the tests!")

    os.Exit(exitVal)
}

func TestA(t *testing.T) {
    log.Println("TestA running")
}

func TestB(t *testing.T) {
    log.Println("TestB running")
}
2020/08/31 20:04:45 Do stuff BEFORE the tests!
2020/08/31 20:04:45 TestA running
2020/08/31 20:04:45 TestB running
PASS
2020/08/31 20:04:45 Do stuff AFTER the tests!
ok      github.com/fan-ADN/test-sample  0.009s
  • 名前からmainをテストする用のものと勘違いしたが、そうではないらしい
  • TestMainを書いていれば、TestXXXが直接実行されずにTestMainm.Run()で実行するので、前後に処理を挟めると言うことらしい
  • 同一パッケージ内に1回しか定義できない

なるほどねー

参考