简介

testify可以说是最流行的(从 GitHub star 数来看)Go 语言测试库了。testify提供了很多方便的函数帮助我们做assert和错误信息输出。使用标准库testing,我们需要自己编写各种条件判断,根据判断结果决定输出对应的信息。

testify核心有三部分内容:

  • assert:断言;
  • mock:测试替身;
  • suite:测试套件。

准备工作

本文代码使用 Go Modules。

创建目录并初始化:

  1. $ mkdir -p testify && cd testify
  2. $ go mod init github.com/go-quiz/go-daily-lib/testify

安装testify库:

  1. $ go get -u github.com/stretchr/testify

assert

assert子库提供了便捷的断言函数,可以大大简化测试代码的编写。总的来说,它将之前需要判断 + 信息输出的模式

  1. if got != expected {
  2. t.Errorf("Xxx failed expect:%d got:%d", got, expected)
  3. }

简化为一行断言代码:

  1. assert.Equal(t, got, expected, "they should be equal")

结构更清晰,更可读。熟悉其他语言测试框架的开发者对assert的相关用法应该不会陌生。此外,assert中的函数会自动生成比较清晰的错误描述信息:

  1. func TestEqual(t *testing.T) {
  2. var a = 100
  3. var b = 200
  4. assert.Equal(t, a, b, "")
  5. }

使用testify编写测试代码与testing一样,测试文件为_test.go,测试函数为TestXxx。使用go test命令运行测试:

  1. $ go test
  2. --- FAIL: TestEqual (0.00s)
  3. assert_test.go:12:
  4. Error Trace:
  5. Error: Not equal:
  6. expected: 100
  7. actual : 200
  8. Test: TestEqual
  9. FAIL
  10. exit status 1
  11. FAIL github.com/go-quiz/go-daily-lib/testify/assert 0.107s

我们看到信息更易读。

testify提供的assert类函数众多,每种函数都有两个版本,一个版本是函数名不带f的,一个版本是带f的,区别就在于带f的函数,我们需要指定至少两个参数,一个格式化字符串format,若干个参数args

  1. func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{})
  2. func Equalf(t TestingT, expected, actual interface{}, msg string, args ...interface{})

实际上,在Equalf()函数内部调用了Equal()

  1. func Equalf(t TestingT, expected interface{}, actual interface{}, msg string, args ...interface{}) bool {
  2. if h, ok := t.(tHelper); ok {
  3. h.Helper()
  4. }
  5. return Equal(t, expected, actual, append([]interface{}{msg}, args...)...)
  6. }

所以,我们只需要关注不带f的版本即可。

Contains

函数类型:

  1. func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool

Contains断言s包含contains。其中s可以是字符串,数组/切片,map。相应地,contains为子串,数组/切片元素,map 的键。

DirExists

函数类型:

  1. func DirExists(t TestingT, path string, msgAndArgs ...interface{}) bool

DirExists断言路径path是一个目录,如果path不存在或者是一个文件,断言失败。

ElementsMatch

函数类型:

  1. func ElementsMatch(t TestingT, listA, listB interface{}, msgAndArgs ...interface{}) bool

ElementsMatch断言listAlistB包含相同的元素,忽略元素出现的顺序。listA/listB必须是数组或切片。如果有重复元素,重复元素出现的次数也必须相等。

Empty

函数类型:

  1. func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool

Empty断言object是空,根据object中存储的实际类型,空的含义不同:

  • 指针:nil
  • 整数:0;
  • 浮点数:0.0;
  • 字符串:空串""
  • 布尔:false;
  • 切片或 channel:长度为 0。

EqualError

函数类型:

  1. func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool

EqualError断言theError.Error()的返回值与errString相等。

EqualValues

函数类型:

  1. func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool

EqualValues断言expectedactual相等,或者可以转换为相同的类型,并且相等。这个条件比Equal更宽,Equal()返回trueEqualValues()肯定也返回true,反之则不然。实现的核心是下面两个函数,使用了reflect.DeapEqual()

  1. func ObjectsAreEqual(expected, actual interface{}) bool {
  2. if expected == nil || actual == nil {
  3. return expected == actual
  4. }
  5. exp, ok := expected.([]byte)
  6. if !ok {
  7. return reflect.DeepEqual(expected, actual)
  8. }
  9. act, ok := actual.([]byte)
  10. if !ok {
  11. return false
  12. }
  13. if exp == nil || act == nil {
  14. return exp == nil && act == nil
  15. }
  16. return bytes.Equal(exp, act)
  17. }
  18. func ObjectsAreEqualValues(expected, actual interface{}) bool {
  19. // 如果`ObjectsAreEqual`返回 true,直接返回
  20. if ObjectsAreEqual(expected, actual) {
  21. return true
  22. }
  23. actualType := reflect.TypeOf(actual)
  24. if actualType == nil {
  25. return false
  26. }
  27. expectedValue := reflect.ValueOf(expected)
  28. if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) {
  29. // 尝试类型转换
  30. return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual)
  31. }
  32. return false
  33. }

例如我基于int定义了一个新类型MyInt,它们的值都是 100,Equal()调用将返回 false,EqualValues()会返回 true:

  1. type MyInt int
  2. func TestEqual(t *testing.T) {
  3. var a = 100
  4. var b MyInt = 100
  5. assert.Equal(t, a, b, "")
  6. assert.EqualValues(t, a, b, "")
  7. }

Error

函数类型:

  1. func Error(t TestingT, err error, msgAndArgs ...interface{}) bool

Error断言err不为nil

ErrorAs

函数类型:

  1. func ErrorAs(t TestingT, err error, target interface{}, msgAndArgs ...interface{}) bool

ErrorAs断言err表示的 error 链中至少有一个和target匹配。这个函数是对标准库中errors.As的包装。

ErrorIs

函数类型:

  1. func ErrorIs(t TestingT, err, target error, msgAndArgs ...interface{}) bool

ErrorIs断言err的 error 链中有target

逆断言

上面的断言都是它们的逆断言,例如NotEqual/NotEqualValues等。

Assertions 对象

观察到上面的断言都是以TestingT为第一个参数,需要大量使用时比较麻烦。testify提供了一种方便的方式。先以*testing.T创建一个*Assertions对象,Assertions定义了前面所有的断言方法,只是不需要再传入TestingT参数了。

  1. func TestEqual(t *testing.T) {
  2. assertions := assert.New(t)
  3. assertion.Equal(a, b, "")
  4. // ...
  5. }

顺带提一句TestingT是一个接口,对*testing.T做了一个简单的包装:

  1. type TestingT interface{
  2. Errorf(format string, args ...interface{})
  3. }

require

require提供了和assert同样的接口,但是遇到错误时,require直接终止测试,而assert返回false

mock

testify提供了对 Mock 的简单支持。Mock 简单来说就是构造一个仿对象,仿对象提供和原对象一样的接口,在测试中用仿对象来替换原对象。这样我们可以在原对象很难构造,特别是涉及外部资源(数据库,访问网络等)。例如,我们现在要编写一个从一个站点拉取用户列表信息的程序,拉取完成之后程序显示和分析。如果每次都去访问网络会带来极大的不确定性,甚至每次返回不同的列表,这就给测试带来了极大的困难。我们可以使用 Mock 技术。

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. )
  8. type User struct {
  9. Name string
  10. Age int
  11. }
  12. type ICrawler interface {
  13. GetUserList() ([]*User, error)
  14. }
  15. type MyCrawler struct {
  16. url string
  17. }
  18. func (c *MyCrawler) GetUserList() ([]*User, error) {
  19. resp, err := http.Get(c.url)
  20. if err != nil {
  21. return nil, err
  22. }
  23. defer resp.Body.Close()
  24. data, err := ioutil.ReadAll(resp.Body)
  25. if err != nil {
  26. return nil, err
  27. }
  28. var userList []*User
  29. err = json.Unmarshal(data, &userList)
  30. if err != nil {
  31. return nil, err
  32. }
  33. return userList, nil
  34. }
  35. func GetAndPrintUsers(crawler ICrawler) {
  36. users, err := crawler.GetUserList()
  37. if err != nil {
  38. return
  39. }
  40. for _, u := range users {
  41. fmt.Println(u)
  42. }
  43. }

Crawler.GetUserList()方法完成爬取和解析操作,返回用户列表。为了方便 Mock,GetAndPrintUsers()函数接受一个ICrawler接口。现在来定义我们的 Mock 对象,实现ICrawler接口:

  1. package main
  2. import (
  3. "github.com/stretchr/testify/mock"
  4. "testing"
  5. )
  6. type MockCrawler struct {
  7. mock.Mock
  8. }
  9. func (m *MockCrawler) GetUserList() ([]*User, error) {
  10. args := m.Called()
  11. return args.Get(0).([]*User), args.Error(1)
  12. }
  13. var (
  14. MockUsers []*User
  15. )
  16. func init() {
  17. MockUsers = append(MockUsers, &User{"dj", 18})
  18. MockUsers = append(MockUsers, &User{"zhangsan", 20})
  19. }
  20. func TestGetUserList(t *testing.T) {
  21. crawler := new(MockCrawler)
  22. crawler.On("GetUserList").Return(MockUsers, nil)
  23. GetAndPrintUsers(crawler)
  24. crawler.AssertExpectations(t)
  25. }

实现GetUserList()方法时,需要调用Mock.Called()方法,传入参数(示例中无参数)。Called()会返回一个mock.Arguments对象,该对象中保存着返回的值。它提供了对基本类型和error的获取方法Int()/String()/Bool()/Error(),和通用的获取方法Get(),通用方法返回interface{},需要类型断言为具体类型,它们都接受一个表示索引的参数。

crawler.On("GetUserList").Return(MockUsers, nil)是 Mock 发挥魔法的地方,这里指示调用GetUserList()方法的返回值分别为MockUsersnil,返回值在上面的GetUserList()方法中被Arguments.Get(0)Arguments.Error(1)获取。

最后crawler.AssertExpectations(t)对 Mock 对象做断言。

运行:

  1. $ go test
  2. &{dj 18}
  3. &{zhangsan 20}
  4. PASS
  5. ok github.com/go-quiz/testify 0.258s

GetAndPrintUsers()函数功能正常执行,并且我们通过 Mock 提供的用户列表也能正确获取。

使用 Mock,我们可以精确断言某方法以特定参数的调用次数,Times(n int),它有两个便捷函数Once()/Twice()。下面我们要求函数Hello(n int)要以参数 1 调用 1次,参数 2 调用两次,参数 3 调用 3 次:

  1. type IExample interface {
  2. Hello(n int) int
  3. }
  4. type Example struct {
  5. }
  6. func (e *Example) Hello(n int) int {
  7. fmt.Printf("Hello with %d\n", n)
  8. return n
  9. }
  10. func ExampleFunc(e IExample) {
  11. for n := 1; n <= 3; n++ {
  12. for i := 0; i <= n; i++ {
  13. e.Hello(n)
  14. }
  15. }
  16. }

编写 Mock 对象:

  1. type MockExample struct {
  2. mock.Mock
  3. }
  4. func (e *MockExample) Hello(n int) int {
  5. args := e.Mock.Called(n)
  6. return args.Int(0)
  7. }
  8. func TestExample(t *testing.T) {
  9. e := new(MockExample)
  10. e.On("Hello", 1).Return(1).Times(1)
  11. e.On("Hello", 2).Return(2).Times(2)
  12. e.On("Hello", 3).Return(3).Times(3)
  13. ExampleFunc(e)
  14. e.AssertExpectations(t)
  15. }

运行:

  1. $ go test
  2. --- FAIL: TestExample (0.00s)
  3. panic:
  4. assert: mock: The method has been called over 1 times.
  5. Either do one more Mock.On("Hello").Return(...), or remove extra call.
  6. This call was unexpected:
  7. Hello(int)
  8. 0: 1
  9. at: [equal_test.go:13 main.go:22] [recovered]

原来ExampleFunc()函数中<=应该是<导致多调用了一次,修改过来继续运行:

  1. $ go test
  2. PASS
  3. ok github.com/go-quiz/testify 0.236s

我们还可以设置以指定参数调用会导致 panic,测试程序的健壮性:

  1. e.On("Hello", 100).Panic("out of range")

suite

testify提供了测试套件的功能(TestSuite),testify测试套件只是一个结构体,内嵌一个匿名的suite.Suite结构。测试套件中可以包含多个测试,它们可以共享状态,还可以定义钩子方法执行初始化和清理操作。钩子都是通过接口来定义的,实现了这些接口的测试套件结构在运行到指定节点时会调用对应的方法。

  1. type SetupAllSuite interface {
  2. SetupSuite()
  3. }

如果定义了SetupSuite()方法(即实现了SetupAllSuite接口),在套件中所有测试开始运行前调用这个方法。对应的是TearDownAllSuite

  1. type TearDownAllSuite interface {
  2. TearDownSuite()
  3. }

如果定义了TearDonwSuite()方法(即实现了TearDownSuite接口),在套件中所有测试运行完成后调用这个方法。

  1. type SetupTestSuite interface {
  2. SetupTest()
  3. }

如果定义了SetupTest()方法(即实现了SetupTestSuite接口),在套件中每个测试执行前都会调用这个方法。对应的是TearDownTestSuite

  1. type TearDownTestSuite interface {
  2. TearDownTest()
  3. }

如果定义了TearDownTest()方法(即实现了TearDownTest接口),在套件中每个测试执行后都会调用这个方法。

还有一对接口BeforeTest/AfterTest,它们分别在每个测试运行前/后调用,接受套件名和测试名作为参数。

我们来编写一个测试套件结构作为演示:

  1. type MyTestSuit struct {
  2. suite.Suite
  3. testCount uint32
  4. }
  5. func (s *MyTestSuit) SetupSuite() {
  6. fmt.Println("SetupSuite")
  7. }
  8. func (s *MyTestSuit) TearDownSuite() {
  9. fmt.Println("TearDownSuite")
  10. }
  11. func (s *MyTestSuit) SetupTest() {
  12. fmt.Printf("SetupTest test count:%d\n", s.testCount)
  13. }
  14. func (s *MyTestSuit) TearDownTest() {
  15. s.testCount++
  16. fmt.Printf("TearDownTest test count:%d\n", s.testCount)
  17. }
  18. func (s *MyTestSuit) BeforeTest(suiteName, testName string) {
  19. fmt.Printf("BeforeTest suite:%s test:%s\n", suiteName, testName)
  20. }
  21. func (s *MyTestSuit) AfterTest(suiteName, testName string) {
  22. fmt.Printf("AfterTest suite:%s test:%s\n", suiteName, testName)
  23. }
  24. func (s *MyTestSuit) TestExample() {
  25. fmt.Println("TestExample")
  26. }

这里只是简单在各个钩子函数中打印信息,统计执行完成的测试数量。由于要借助go test运行,所以需要编写一个TestXxx函数,在该函数中调用suite.Run()运行测试套件:

  1. func TestExample(t *testing.T) {
  2. suite.Run(t, new(MyTestSuit))
  3. }

suite.Run(t, new(MyTestSuit))会将运行MyTestSuit中所有名为TestXxx的方法。运行:

  1. $ go test
  2. SetupSuite
  3. SetupTest test count:0
  4. BeforeTest suite:MyTestSuit test:TestExample
  5. TestExample
  6. AfterTest suite:MyTestSuit test:TestExample
  7. TearDownTest test count:1
  8. TearDownSuite
  9. PASS
  10. ok github.com/go-quiz/testify 0.375s

测试 HTTP 服务器

Go 标准库提供了一个httptest用于测试 HTTP 服务器。现在编写一个简单的 HTTP 服务器:

  1. func index(w http.ResponseWriter, r *http.Request) {
  2. fmt.Fprintln(w, "Hello World")
  3. }
  4. func greeting(w http.ResponseWriter, r *http.Request) {
  5. fmt.Fprintf(w, "welcome, %s", r.URL.Query().Get("name"))
  6. }
  7. func main() {
  8. mux := http.NewServeMux()
  9. mux.HandleFunc("/", index)
  10. mux.HandleFunc("/greeting", greeting)
  11. server := &http.Server{
  12. Addr: ":8080",
  13. Handler: mux,
  14. }
  15. if err := server.ListenAndServe(); err != nil {
  16. log.Fatal(err)
  17. }
  18. }

很简单。httptest提供了一个ResponseRecorder类型,它实现了http.ResponseWriter接口,但是它只是记录写入的状态码和响应内容,不会发送响应给客户端。这样我们可以将该类型的对象传给处理器函数。然后构造服务器,传入该对象来驱动请求处理流程,最后测试该对象中记录的信息是否正确:

  1. func TestIndex(t *testing.T) {
  2. recorder := httptest.NewRecorder()
  3. request, _ := http.NewRequest("GET", "/", nil)
  4. mux := http.NewServeMux()
  5. mux.HandleFunc("/", index)
  6. mux.HandleFunc("/greeting", greeting)
  7. mux.ServeHTTP(recorder, request)
  8. assert.Equal(t, recorder.Code, 200, "get index error")
  9. assert.Contains(t, recorder.Body.String(), "Hello World", "body error")
  10. }
  11. func TestGreeting(t *testing.T) {
  12. recorder := httptest.NewRecorder()
  13. request, _ := http.NewRequest("GET", "/greeting", nil)
  14. request.URL.RawQuery = "name=dj"
  15. mux := http.NewServeMux()
  16. mux.HandleFunc("/", index)
  17. mux.HandleFunc("/greeting", greeting)
  18. mux.ServeHTTP(recorder, request)
  19. assert.Equal(t, recorder.Code, 200, "greeting error")
  20. assert.Contains(t, recorder.Body.String(), "welcome, dj", "body error")
  21. }

运行:

  1. $ go test
  2. PASS
  3. ok github.com/go-quiz/go-daily-lib/testify/httptest 0.093s

很简单,没有问题。

但是我们发现一个问题,上面的很多代码有重复,recorder/mux等对象的创建,处理器函数的注册。使用suite我们可以集中创建,省略这些重复的代码:

  1. type MySuite struct {
  2. suite.Suite
  3. recorder *httptest.ResponseRecorder
  4. mux *http.ServeMux
  5. }
  6. func (s *MySuite) SetupSuite() {
  7. s.recorder = httptest.NewRecorder()
  8. s.mux = http.NewServeMux()
  9. s.mux.HandleFunc("/", index)
  10. s.mux.HandleFunc("/greeting", greeting)
  11. }
  12. func (s *MySuite) TestIndex() {
  13. request, _ := http.NewRequest("GET", "/", nil)
  14. s.mux.ServeHTTP(s.recorder, request)
  15. s.Assert().Equal(s.recorder.Code, 200, "get index error")
  16. s.Assert().Contains(s.recorder.Body.String(), "Hello World", "body error")
  17. }
  18. func (s *MySuite) TestGreeting() {
  19. request, _ := http.NewRequest("GET", "/greeting", nil)
  20. request.URL.RawQuery = "name=dj"
  21. s.mux.ServeHTTP(s.recorder, request)
  22. s.Assert().Equal(s.recorder.Code, 200, "greeting error")
  23. s.Assert().Contains(s.recorder.Body.String(), "welcome, dj", "body error")
  24. }

最后编写一个TestXxx驱动测试:

  1. func TestHTTP(t *testing.T) {
  2. suite.Run(t, new(MySuite))
  3. }

总结

testify扩展了testing标准库,断言库assert,测试替身mock和测试套件suite,让我们编写测试代码更容易!

大家如果发现好玩、好用的 Go 语言库,欢迎到 Go 每日一库 GitHub 上提交 issue😄

参考

  1. testify GitHub:github.com/stretchr/testify
  2. Go 每日一库 GitHub:https://github.com/go-quiz/go-daily-lib