golang testing设置单个case和所有case的se

2021-08-30  本文已影响0人  CodingCode

例子:

  1. setUpAll在所有case启动前运行一次
  2. tearDownAll在所有case结束后运行一次
  3. setUp在每个case启动前运行一次
  4. tearDown在每个case结束后运行一次
package main

import (
    "log"
    "os"

    "testing"
)

func TestMain(m *testing.M) {
    tearDownAll := setUpAll()

    code := m.Run()

    tearDownAll()   // you cannot use defer tearDownAll()
    os.Exit(code)
}

func setUpAll() func() {
    log.Printf("LLLLLLLL: setUpAll")
    return func() {
        log.Printf("LLLLLLLL: tearDownAll")
    }
}

func setUp(t *testing.T) func(t *testing.T) {
    log.Printf("LLLLLLLL: setUp");

    return func(t *testing.T) {
        log.Printf("LLLLLLLL: tearDown")
    }
}


func TestBasic1(t *testing.T) {
    tearDown := setUp(t)
    defer tearDown(t)

    log.Printf("LLLLLLLL: TestBasic1")
}
func TestBasic2(t *testing.T) {
    tearDown := setUp(t)
    defer tearDown(t)

    log.Printf("LLLLLLLL: TestBasic2")
}
func TestBasic3(t *testing.T) {
    tearDown := setUp(t)
    defer tearDown(t)

    log.Printf("LLLLLLLL: TestBasic3")
}

运行:

$ go test -v -run Basic
2021/08/30 06:08:20 LLLLLLLL: setUpAll
=== RUN   TestBasic1
2021/08/30 06:08:20 LLLLLLLL: setUp
2021/08/30 06:08:20 LLLLLLLL: TestBasic1
2021/08/30 06:08:20 LLLLLLLL: tearDown
--- PASS: TestBasic1 (0.00s)
=== RUN   TestBasic2
2021/08/30 06:08:20 LLLLLLLL: setUp
2021/08/30 06:08:20 LLLLLLLL: TestBasic2
2021/08/30 06:08:20 LLLLLLLL: tearDown
--- PASS: TestBasic2 (0.00s)
=== RUN   TestBasic3
2021/08/30 06:08:20 LLLLLLLL: setUp
2021/08/30 06:08:20 LLLLLLLL: TestBasic3
2021/08/30 06:08:20 LLLLLLLL: tearDown
--- PASS: TestBasic3 (0.00s)
PASS
2021/08/30 06:08:20 LLLLLLLL: tearDownAll
ok      _/<pwd> 0.003s
上一篇下一篇

猜你喜欢

热点阅读