【GO】22.go 测试库 convey

  • 下载convey库:

go get github.com/smartystreets/goconvey

 

  • 测试函数

some_functions.go

package goconveydemo

import "errors"

func IsEqual(a, b int) bool{
	return a == b
}

func IsEqualWithErr(a, b int) (bool, error){
	if a > b {
		return false, errors.New("over")
	} else if a < b{
		return false, errors.New("under")
	} else{
		return true, nil
	}
}

 

  • 测试用例

goconvey_test.go

package goconveydemo

import (
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestSpec(t *testing.T) {
	// Only pass t into top-level Convey calls
	Convey("Given some integer with a starting value", t, func() {
		x := 1

		Convey("When the integer is incremented", func() {
			x++

			Convey("The value should be greater by one", func() {
				So(x, ShouldEqual, 2)
			})
		})
	})
}

func TestIsEqual(t *testing.T){
	Convey("1 == 1", t, func() {
		So(IsEqual(1, 1), ShouldBeTrue)
	})
}

func TestIsEqualWithErr(t *testing.T){
	Convey("IsEqualWithErr", t, func(){
		Convey("2 > 1, over", func(){
			ok, err := IsEqualWithErr(2, 1)
			So(ok, ShouldBeFalse)
			So(err, ShouldNotBeNil)
		})

		Convey("1 < 2, under", func(){
			ok, err := IsEqualWithErr(1, 2)
			So(ok, ShouldBeFalse)
			So(err, ShouldNotBeNil)
		})

		Convey("1 = 1, equal", func(){
			ok, err := IsEqualWithErr(1, 1)
			So(ok, ShouldBeTrue)
			So(err, ShouldBeNil)
		})
	})
}

 

  • 运行$GOPATH/bin目录下生成的goconvey程序,打开http://localhost:8080

【GO】22.go 测试库 convey_第1张图片

 

  • 运行go test -v

【GO】22.go 测试库 convey_第2张图片

 

  •  PS:golang test单元测试规范

  • 文件名必须是_test.go结尾的,这样在执行go test的时候才会执行到相应的代码
  • 你必须import testing这个包
  • 所有的测试用例函数必须是Test开头
  • 测试用例会按照源代码中写的顺序依次执行
  • 测试函数TestXxx()的参数是testing.T,我们可以使用该类型来记录错误或者是测试状态
  • 测试格式:func TestXxx (t *testing.T),Xxx部分可以为任意的字母数字的组合,但是首字母不能是小写字母[a-z],例如Testintdiv是错误的函数名。
  • 函数中通过调用testing.TErrorErrorfFailNowFatalFatalIf方法,说明测试不通过,调用Log方法用来记录测试的信息。

 

  • 注意

当gotest运行具体文件时,需要把依赖的文件一起打出来,否则会报错。

如本例

go test -v goconvey_test.go

//输出
# command-line-arguments [command-line-arguments.test]
./goconvey_test.go:25:6: undefined: IsEqual
./goconvey_test.go:32:15: undefined: IsEqualWithErr
./goconvey_test.go:38:15: undefined: IsEqualWithErr
./goconvey_test.go:44:15: undefined: IsEqualWithErr
FAIL	command-line-arguments [build failed]

正确写法如下

go test -v goconvey_test.go some_functions.go

//输出
=== RUN   TestSpec

  Given some integer with a starting value 
    When the integer is incremented 
      The value should be greater by one ✔


1 total assertion

--- PASS: TestSpec (0.00s)
=== RUN   TestIsEqual

  1 == 1 ✔


2 total assertions

--- PASS: TestIsEqual (0.00s)
=== RUN   TestIsEqualWithErr

  IsEqualWithErr 
    2 > 1, over ✔✔
    1 < 2, under ✔✔
    1 = 1, equal ✔✔


8 total assertions

--- PASS: TestIsEqualWithErr (0.00s)
PASS
ok  	command-line-arguments	0.006s

 

你可能感兴趣的:(Go技术积累)