Golang 筆記
  • Introduction
  • 安裝Golang
    • 本地編譯與安裝第三方套件
    • 第一個 GO 程式
    • export 與 import
    • 使用 go mod
  • 基本工具
  • DataBase操作
    • MySQL
    • 使用 ORM
    • MongoDB
  • 基本語法
    • Variable
    • BSON
    • JSON
    • 時間相關
    • Interface
    • Error
    • 型別
    • 字串
    • defer
    • panic, recover
    • Channel 與Goroutine
      • 讀寫鎖
      • for select 與 for range
      • UnBuffered channel 與 Buffered channel
    • Function
    • pointer
    • regExp
    • fmt
    • Make vs New
    • struct
    • Array, Slice 陣列
    • map
  • 核心模組
    • Reflect
    • File
    • Signal
    • BuiltIn
    • Sync
    • IO
    • Sort
    • http
    • crypto
    • context
  • 第三方模組
    • Dom Parser
    • gin 框架
    • Websocket
    • Iris框架
      • 讀取 Body 資料
      • 相關範例
    • Fiber 框架
    • 自動重啟 server 工具
    • go-jwt
  • 測試
  • 原始碼解析
  • 常見問題
    • 資料存取不正確
    • Data races
Powered by GitBook
On this page

測試

Previousgo-jwtNext原始碼解析

Last updated 5 years ago

Was this helpful?

CtrlK
  • 撰寫測試
  • Benchmark

Was this helpful?

執行以上後會顯示出如下

f1     10000        120860 ns/op        2433 B/op         28 allocs/op
f2     10000        120288 ns/op        2288 B/op         26 allocs/op

其中分別為

1. 疊代次数
2. ns/op 是一次疊代完成所需的時間奈秒
3. allocs/op 表示每個op發生多少個內存分配
4. B/op 是每個操作分配了多少 bytes 。

撰寫測試

1.先在目錄內新增一個main.go (如果沒有其他go檔案test會錯誤)

2.新增 ...test.go (任何名稱加上 _test.go)

3.輸入 go test <package name>

會自動去尋找目錄內 _test.go檔案,然後其中 名稱包含Test的func

新增如下,然後把 1改成 2看看

package hello

import "testing"

func Test123(t *testing.T) {
    if 1 != 1 {
        t.Fail()
    }
}

其他可用包含

t.Skip()
t.Error()
t.Log(...)

Benchmark

任何以func BenchmarkXxx(b *testing.B) 都會跑效能測試

package hello

import "testing"

func Add(a, b int) int {
    return a + b
}
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}

然後輸入go test hello -bench="."

想看到 Log 的訊息的話,必須加上 -v 引數, 加上 -bench 引數可指定要測試的函式名稱