- 为何使用它,if else 高度封装
安装 go get github.com/smartystreets/goconvey
使用
- 准备业务代码 student.go
package mainimport "fmt"type Student struct {Name stringChiScore intEngScore intMathScore int}func NewStudent(name string) (*Student, error) {if name == "" {return nil, fmt.Errorf("name为空")}return &Student{Name: name,}, nil}func (s *Student) GetAvgScore() (int, error) {score := s.ChiScore + s.EngScore + s.MathScoreif score == 0 {return 0, fmt.Errorf("全都是0分")}return score / 3, nil}
- 准备测试用例 student_test.go
package mainimport ("testing". "github.com/smartystreets/goconvey/convey")func TestNewStudent(t *testing.T) {Convey("start test new", t, func() {stu, err := NewStudent("")Convey("空的name初始化错误", func() {So(err, ShouldBeError)})Convey("stu对象为nil", func() {So(stu, ShouldBeNil)})})}func TestScore(t *testing.T) {stu, _ := NewStudent("小乙")Convey("不设置分数可能出错", t, func() {sc, err := stu.GetAvgScore()Convey("获取分数出错了", func() {So(err, ShouldBeError)})Convey("分数为0", func() {So(sc, ShouldEqual, 0)})})Convey("正常情况", t, func() {stu.ChiScore = 60stu.EngScore = 70stu.MathScore = 80score, err := stu.GetAvgScore()Convey("获取分数出错了", func() {So(err, ShouldBeNil)})Convey("平均分大于60", func() {So(score, ShouldBeGreaterThan, 60)})})}
- 执行 go test -v .
=== RUN TestNewStudentstart test new空的name初始化错误 .stu对象为nil .2 total assertions--- PASS: TestNewStudent (0.00s)=== RUN TestScore不设置分数可能出错获取分数出错了 .分数为0 .4 total assertions正常情况获取分数出错了 .平均分大于60 .6 total assertions--- PASS: TestScore (0.00s)PASSok pkg007 (cached)
图形化使用
- 确保本地有goconvey的二进制
- go get github.com/smartystreets/goconvey 我使用的是这个
- go get github.com/smartystreets/goconvey/convey
- 会将对应的二进制放到 $GOPATH/bin 下面
- 编辑环境变量把 $GOPATH/bin 加入PATH里面 或者写全路径
- 到测试的目录下,执行goconvey ,启动http 8000,自动跑测试用例
- 浏览器方位 127.0.0.1:8000
