• 为何使用它,if else 高度封装

安装 go get github.com/smartystreets/goconvey

使用

  • 准备业务代码 student.go
  1. package main
  2. import "fmt"
  3. type Student struct {
  4. Name string
  5. ChiScore int
  6. EngScore int
  7. MathScore int
  8. }
  9. func NewStudent(name string) (*Student, error) {
  10. if name == "" {
  11. return nil, fmt.Errorf("name为空")
  12. }
  13. return &Student{
  14. Name: name,
  15. }, nil
  16. }
  17. func (s *Student) GetAvgScore() (int, error) {
  18. score := s.ChiScore + s.EngScore + s.MathScore
  19. if score == 0 {
  20. return 0, fmt.Errorf("全都是0分")
  21. }
  22. return score / 3, nil
  23. }
  • 准备测试用例 student_test.go
  1. package main
  2. import (
  3. "testing"
  4. . "github.com/smartystreets/goconvey/convey"
  5. )
  6. func TestNewStudent(t *testing.T) {
  7. Convey("start test new", t, func() {
  8. stu, err := NewStudent("")
  9. Convey("空的name初始化错误", func() {
  10. So(err, ShouldBeError)
  11. })
  12. Convey("stu对象为nil", func() {
  13. So(stu, ShouldBeNil)
  14. })
  15. })
  16. }
  17. func TestScore(t *testing.T) {
  18. stu, _ := NewStudent("小乙")
  19. Convey("不设置分数可能出错", t, func() {
  20. sc, err := stu.GetAvgScore()
  21. Convey("获取分数出错了", func() {
  22. So(err, ShouldBeError)
  23. })
  24. Convey("分数为0", func() {
  25. So(sc, ShouldEqual, 0)
  26. })
  27. })
  28. Convey("正常情况", t, func() {
  29. stu.ChiScore = 60
  30. stu.EngScore = 70
  31. stu.MathScore = 80
  32. score, err := stu.GetAvgScore()
  33. Convey("获取分数出错了", func() {
  34. So(err, ShouldBeNil)
  35. })
  36. Convey("平均分大于60", func() {
  37. So(score, ShouldBeGreaterThan, 60)
  38. })
  39. })
  40. }
  • 执行 go test -v .
  1. === RUN TestNewStudent
  2. start test new
  3. 空的name初始化错误 .
  4. stu对象为nil .
  5. 2 total assertions
  6. --- PASS: TestNewStudent (0.00s)
  7. === RUN TestScore
  8. 不设置分数可能出错
  9. 获取分数出错了 .
  10. 分数为0 .
  11. 4 total assertions
  12. 正常情况
  13. 获取分数出错了 .
  14. 平均分大于60 .
  15. 6 total assertions
  16. --- PASS: TestScore (0.00s)
  17. PASS
  18. ok pkg007 (cached)

图形化使用

  1. 确保本地有goconvey的二进制
  • go get github.com/smartystreets/goconvey 我使用的是这个
  • go get github.com/smartystreets/goconvey/convey
  • 会将对应的二进制放到 $GOPATH/bin 下面
  1. 编辑环境变量把 $GOPATH/bin 加入PATH里面 或者写全路径
  2. 到测试的目录下,执行goconvey ,启动http 8000,自动跑测试用例
  3. 浏览器方位 127.0.0.1:8000