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
が直接実行されずにTestMain
内m.Run()
で実行するので、前後に処理を挟めると言うことらしい
- 同一パッケージ内に1回しか定義できない
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
が直接実行されずにTestMain
内m.Run()
で実行するので、前後に処理を挟めると言うことらしいなるほどねー
参考
Author And Source
この問題について(Goのテストでset-upとtear-down), 我々は、より多くの情報をここで見つけました https://qiita.com/yotsak/items/4e121842c4122c6dffc5著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .