1,gomonkey代码的地址:
https://github.com/agiledragon/gomonkey
2,从命令行安装gomonkey
liuhongdi@ku:~$ go get -u github.com/agiledragon/gomonkey
3,goconvey库的代码地址
https://github.com/smartystreets/goconvey
4,从命令行安装
liuhongdi@ku:~$ go get -u github.com/smartystreets/goconvey
说明:刘宏缔的go森林是一个专注golang的博客,
地址:https://blog.csdn.net/weixin_43881017
说明:作者:刘宏缔 邮箱: [email protected]
1,项目地址:
https://github.com/liuhongdi/unittest03
2,功能说明:演示了使用gomonkey库在项目中测试时打桩
3,项目结构:如图:
1,model/user.go
package model
type MyUser struct {
name string
}
//返回用户的name
func (s *MyUser) GetUserName() string {
return s.name
}
2,main.go
package main
//定义一个加法方法
func Add(a, b int) int {
return a + b
}
//定义方法,返回一个整数的2倍
func GetDouble(a int) int {
return Add(a,a)
}
3,main_test.go
package main
import (
. "github.com/agiledragon/gomonkey"
"github.com/liuhongdi/unittest03/model"
. "github.com/smartystreets/goconvey/convey"
"reflect"
"testing"
)
//测试double,为add函数打桩1
func TestDoubleRight(t *testing.T) {
patch := ApplyFunc(Add, func(a,b int) int {
return a * 2
})
defer patch.Reset()
//fmt.Println(GetDouble(2))
Convey("test 2 x 2", t, func() {
So(GetDouble(2), ShouldEqual,4)
})
}
//add函数的桩子
func addstub(a,b int) int {
return a*3
}
//测试double,为add函数打桩2
func TestDoubleError(t *testing.T) {
patch := ApplyFunc(Add, addstub)
defer patch.Reset()
//fmt.Println(GetDouble(2))
Convey("test 2 x 2", t, func() {
So(GetDouble(2), ShouldEqual,4)
})
}
//测试给方法打桩1,返回正确
func TestMethodRight(t *testing.T) {
var temp *model.MyUser
patch := ApplyMethod(reflect.TypeOf(temp), "GetUserName", func(_ *model.MyUser) string {
return "hello,world!"
})
defer patch.Reset()
Convey("GetUserName将返回:hello,world!", t, func() {
var user *model.MyUser
user = new(model.MyUser)
So(user.GetUserName(), ShouldEqual, "hello,world!")
})
}
//测试给方法打桩2,返回错误
func TestMethodError(t *testing.T) {
var temp *model.MyUser
patch := ApplyMethod(reflect.TypeOf(temp), "GetUserName", func(_ *model.MyUser) string {
return "hello,老刘!"
})
defer patch.Reset()
Convey("GetUserName将返回:hello,world!", t, func() {
var user *model.MyUser
user = new(model.MyUser)
So(user.GetUserName(), ShouldEqual, "hello,world!")
})
}
执行测试:
root@ku:/data/go/unittest03# go test -v ./... -gcflags "all=-N -l"
注意:添加参数:-gcflags "all=-N -l"
否则打桩可能不会生效
返回:
module github.com/liuhongdi/unittest03
go 1.15
require (
github.com/smartystreets/goconvey v1.6.4
github.com/agiledragon/gomonkey v2.0.2+incompatible
)