Skip to main content

testify規劃方式

這次我們要使用的測試工具是testify https://github.com/stretchr/testify

他除了是一套好用的斷言lib之外(可以幫我們用白話文的方式驗證資料對不對) 他也有提供整理Test程式碼的一套流程出來,這次我主要會使用他提供的Suite這個測試的流程 https://github.com/stretchr/testify#suite-package

他的起手式大致如下

// Basic imports
import (
"testing"
"github.com/stretchr/testify/suite"
)
// In order for 'go test' to run this suite, we need to create
// a normal test function and pass our suite to suite.Run
func TestExampleTestSuite(t *testing.T) {
suite.Run(t, new(ExampleTestSuite))
}

// Define the suite, and absorb the built-in basic suite
// functionality from testify - including assertion methods.
type ExampleTestSuite struct {
suite.Suite
VariableThatShouldStartAtFive int
}

// Make sure that VariableThatShouldStartAtFive is set to five
// before each test
func (suite *ExampleTestSuite) SetupTest() {
suite.VariableThatShouldStartAtFive = 5
}

// All methods that begin with "Test" are run as tests within a
// suite.
func (suite *ExampleTestSuite) TestExample() {
suite.Equal(suite.VariableThatShouldStartAtFive, 5)
}


而會選擇用Suite這個方式來進行測試,有幾個原因

  1. 他有提供方便method,讓我們可以快速的設定在沒次測試前要先運行什麼樣的程式碼,結束後要進行什麼樣的資源回收
  2. 因為是透過同一個struct來進行管理,所以你在每次測試前需要對某些資料進行一些事前準備,就算把這些準備的流程放到SetupTest中,也可以透過ExampleTestSuite這個struct裡面新增一些Property來進行傳遞,就不需要宣告很多全域的變數,污染整個專案
  3. 套用前面的邏輯,如果你有很多驗證都是相同的流程,但驗證的過程很繁複的時候,也可以將相對應的程式碼變成獨立的method,掛在ExampleTestSuite下,這樣不同的測試就可以用到同一組的測試程式碼了,相當方便

以下是我將前兩篇的工具應用完的結果 https://github.com/kevinyay945/2023_asset_management/blob/1c1b1a364199ef869423f1ab33882159031a29d9/interface/rest_api/echo_test.go