【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 test -v

 

  •  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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值