安装 github.com/stretchr/testify/assert

相比较goConvery, 使用者更多 star 更多

使用

  • cal.go
  1. package main
  2. func Add(x int ) (result int) {
  3. result = x +2
  4. return result
  5. }
  • cal_test.go
  1. package main
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestAdd(t *testing.T) {
  7. // assert equality
  8. assert.Equal(t, Add(5), 7, "they should be equal")
  9. }

表驱动测试

  1. package main
  2. import (
  3. "testing"
  4. "github.com/stretchr/testify/assert"
  5. )
  6. func TestAdd(t *testing.T) {
  7. // assert equality
  8. assert.Equal(t, Add(5), 7, "they should be equal")
  9. }
  10. func TestCal(t *testing.T) {
  11. ass := assert.New(t)
  12. var tests = []struct {
  13. input int
  14. expected int
  15. }{
  16. {2, 4},
  17. {-1, 1},
  18. {0, 2},
  19. {-5, -3},
  20. {999999997, 999999999},
  21. }
  22. for _, test := range tests {
  23. ass.Equal(Add(test.input), test.expected)
  24. }
  25. }

mock功能