LoginSignup
3
0

More than 3 years have passed since last update.

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

Last updated at Posted at 2020-08-31

概要

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回しか定義できない

なるほどねー

参考

3
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
3
0