owned this note changed 5 years ago
Linked with GitHub

談談 go 測試的二三事 - David Chou

tags: COSCUP2020 入門 TR214

歡迎來到 https://hackmd.io/@coscup/2020 共筆 :mega:
點擊本頁上方的 開始用 Markdown 一起寫筆記!
手機版請點選上方 按鈕展開議程列表。

請從這裡開始

Unit-test in Golang is simple

because of the build-in testing framework

go test

幾個講者的 tricks

go test -v -run={TestName}
go test -race
go test -count=1 (prevent cache)
go test -c -o {TextExe} (get test code binary)

go test -cover
go tool cover -html=cover.html

Test helpers

testify

提供好用的 assert 函數

  • Nil, NoNil
  • Error, NoError
  • EqualValues, JSONEq
  • Len, True, False, Empty

另外還有一包 require

assertrequire 差異在 assert 會繼續跑,require 會停下

講者建議的 test helper funcs

  • 直接在內部處理 error
  • 可以回傳 func 做 clean up
  • 傳入 t 可以做更多

Table-driven test

  • 把測資寫成map, 並用for loop測試
  • 可以方便引入 parallel 加快測試速度
  • 平行 test 的時候要把 foreach 的變數複製一份

Writing testable code

testable code \(!=\) TDD

that code is testable when we don't have to change the code itself when we're adding unit test.

SOLID principle

依賴反轉 dependency inversion

其中一個實作方法是依賴注入,讓 A 依賴於 A 自己的介面,然後把 B 注入
在單元測試時,可以自由的傳入 mock 的 B

  1. Accept interface, return concrete type

concrete type is usually pointer or struct

  1. Do not define interfaces on the implementor side

Mocking

gomock

  • the official framework

透過寫 go generate comment 去產生骨架

integrate test

ory/dockertest

可以做到整合 go test

工商

GopherCon TW 2020

Select a repo