安利一個好用的Golang單元測試架構:gocheck

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

Golang下如何寫單元測試?官方提供的testing package略顯簡陋,不過好在我們有Gocheck。

什麼是好的單元測試?

在進入正題前,先來溫習下前人總結的單元測試幾條原則:
http://www.atatech.org/articles/2523

1   單元測試應該在最低的功能/參數上驗證程式的正確性...3    單元測試過後,機器狀態保持不變...6    獨立性,單元測試的運行/通過/失敗不依賴於別的測試,可以人為構造資料,以保持單元測試的獨立性。

好的單元測試,應該遵循上面的原則;好的單元測試架構,應該為我們踐行這些原則提供方便。

gocheck,簡單好用

gocheck官網:http://labix.org/gocheck

Golang官方的testing package算是很弱的了:居然連assert都不支援。Gocheck在testing庫之上,豐富了很多功能,帶我們脫離Golang官方測試架構下無盡的“if…else…"苦海。尤其好用的特性包括:

  1. assert斷言 + 豐富的判斷動詞: deep multi-type 對比, 字串比較(甚至支援正則匹配!)。
  2. 按suite組織測試案例,支援suite層級的setup()和teardown()。
  3. 建立、刪除臨時檔案/目錄。

樣本1:檔案操作相關的單元測試

“單元測試過後,機器狀態保持不變”的原則告訴我們,如果單元測試要讀寫檔案,單元測試結束後要清理建立的臨時檔案。

gocheck可以建立一個臨時目錄,在測試結束時自動刪除它,省去了手動清理的步驟。

樣本:

package hello_testimport (    "testing"    "io/ioutil"    "io"    . "gopkg.in/check.v1")const txt = "adfagaggafaf"// Hook up gocheck into the "go test" runner.func Test(t *testing.T) { TestingT(t) }type MySuite struct {    dir string   // 測試用的臨時目錄    f   string   // 測試用的臨時檔案}var _ = Suite(&MySuite{})// Setupsuite 準備測試用的臨時檔案func (s *MySuite) SetUpSuite(c *C) {    dir := c.MkDir()    // Suite結束後會自動銷毀c.MkDir()建立的目錄    tmpfile, err := ioutil.TempFile(dir, "")    if err != nil {        c.Errorf("Fail to create test file: %v\n", tmpfile.Name(), err)    }    err = WriteFile(tmpfile.Name(), txt)    if err != nil {        c.Errorf("Fail to prepare test file.%v\n", tmpfile.Name(), err)    }    s.dir = dir    s.f = tmpfile.Name()   }func (s *MySuite) TestFoo(c *C) {    // ... 實際測試代碼    c.Assert(bkpName, Matches, s.f+".ops_agent_bkp.+")}

樣本2:Mock web api相關的單元測試

“獨立性”的原則告訴我們,對於需要調用外部api的功能,最好mock資料。利用gocheck的SetUpSuite()和TearDownSuite()方法,可以建立一個http test server,結束時關閉它。

樣本:

package hello_testimport (    "fmt"    "net/http"    "net/http/httptest"    "testing"    . "gopkg.in/check.v1")const (    resp1 = `{   "data" : {      "cluster" : "*****",      "hostname" : "xxxxx"   },   "err_code" : 0,   "err_msg" : ""}`    resp2 = `{   "data" : [      {         "hostname" : "e18h13551.XXX",         "ip" : "100.22.33.44",         "state" : "GOOD"      },      {         "hostname" : "dddd",         "ip" : "101.14.12.55",         "state" : "GOOD"      }   ],   "err_code" : 0,   "err_msg" : ""}`)// Hook up gocheck into the "go test" runner.func Test(t *testing.T) { TestingT(t) }type MySuite struct {    ts *httptest.Server}func (s *MySuite) SetUpSuite(c *C) {    h := http.NewServeMux()    h.HandleFunc("/machine", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintln(w, resp1)    })    h.HandleFunc("/batch", func(w http.ResponseWriter, r *http.Request) {        fmt.Fprintln(w, resp2)    })    s.ts = httptest.NewServer(h)}func (s *MySuite) TearDownSuite(c *C) {    s.ts.Close()}var _ = Suite(&MySuite{})func (s *MySuite) TestFoo(c *C) {    // 實際測試代碼....    clusterName, err := getClusterName(s.ts.URL, "/machine")    c.Assert(err, IsNil)    c.Assert(clusterName, Equals, "MiniLVSCluster-5e87-2384205713506559")}

其他

Gocheck其他好用的特性,比如強大的checker 就不在此列舉。可以在官網上翻翻,讓寫單元測試更簡單。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.