1. 程式人生 > 實用技巧 >go test鹹魚筆記

go test鹹魚筆記

$GOPATH中專案目錄下建立 main_test.go 檔案(需要測試的檔案預設以 XXX_test.go 命名)

main.go檔案中有個函式

func Print1to20() int {
  res := 0
  for i := 1; i <= 20; i++ {
	res += i
  }
  return res
}

main_test.go中

package main

import (
  "fmt"
  "testing"
)

func TestPrint(t *testing.T) {//引數 t *testing T    如果測試效能則 b *testing B
  res := Print1to20()
  fmt.Println("hey")
  if res != 210 {
	t.Errorf("Wrong")//t.Errorf列印錯誤資訊
  } }

cmd命令進入專案目錄,執行 go test

執行go test -v

--------------------------------------------------------------------------------------------------

t.SkipNow()表示跳過當前測試函式,t.SkipNow()必須放在測試函式第一行

func TestPrint(t *testing.T) {
  t.SkipNow()//跳過TestPrint內容並繼續下一個test,顯示PASS
  res := Print1to20()
  fmt.Println("hey")
  if res != 210 {
	t.Errorf("Wrong")
  }
}

--------------------------------------------------------------------------------------------------

如果要順序執行各個test,則用到 t.Run(string, func)

func TestPrint(t *testing.T) {
  t.Run("a1",func(t *testing.T){
	fmt.Println("a1")
  })

  t.Run("a3",func(t *testing.T){
	fmt.Println("a2")
  })

  t.Run("a2",func(t *testing.T){
	fmt.Println("a3")
  })
} 

--------------------------------------------------------------------------------------------------

如果要先執行某個test,則用 TestMain(m *testing.M) ,通常執行 檔案開啟 or 登入 or 資料庫連線 等等

func TestMain(m *testing.M){
  fmt.Println("test main first")
  m.Run()//不加 m.Run() 則不能進行後面的test
}