Go Main測試實現原理剖析
阿新 • • 發佈:2019-02-26
簡介
每一種測試(單元測試、效能測試或示例測試),都有一個數據型別與其對應。
- 單元測試:InternalTest
- 效能測試:InternalBenchmark
- 示例測試:InternalExample
測試編譯階段,每個測試都會被放到指定型別的切片中,測試執行時,這些測試將會被放到testing.M資料結構中進行排程。
而testing.M即是MainTest對應的資料結構。
資料結構
原始碼src\testing/testing.go:M
定義了testing.M的資料結構:
// M is a type passed to a TestMain function to run the actual tests. type M struct { tests []InternalTest // 單元測試 benchmarks []InternalBenchmark // 效能測試 examples []InternalExample // 示例測試 timer *time.Timer // 測試超時時間 }
單元測試、效能測試和示例測試在經過編譯後都會被存放到一個testing.M資料結構中,在測試執行時該資料結構將傳遞給TestMain(),真正執行測試的是testing.M的Run()方法,這個後面我們會繼續分析。
timer用於指定測試的超時時間,可以通過引數timeout <n>
指定,當測試執行超時後將會立即結束並判定為失敗。
執行測試
TestMain()函式通常會有一個m.Run()方法,該方法會執行單元測試、效能測試和示例測試,如果使用者實現了TestMain()但沒有呼叫m.Run()的話,那麼什麼測試都不會被執行。
m.Run()不僅會執行測試,還會做一些初始化工作,比如解析引數、起動定時器、跟據引數指示建立一系列的檔案等。
m.Run()使用三個獨立的方法來執行三種測試:
- 單元測試:runTests(m.deps.MatchString, m.tests)
- 效能測試:runExamples(m.deps.MatchString, m.examples)
- 示例測試:runBenchmarks(m.deps.ImportPath(), m.deps.MatchString, m.benchmarks) 其中m.deps裡存放了測試匹配相關的內容,暫時先