原文: https://www.jianshu.com/p/633b55d73ddd

.mock 方法 (interface)
type Student struct {}
func (s Student) Interesting(prodName string) bool{
return true
}
func testFunc(prodName string) bool{
st := &Student{}
result := st.Interesting(prodName)
if false == result {
fmt.Println("Student like product ", prodName)
}
return result
}
测试:
func Test_testFunc(t *testing.T) {
stu := Student{}
patch := ApplyMethod(reflect.TypeOf(stu), "Interesting", func(Student, string) bool {
return true
})
result := testFunc("pen")
So(result, ShouldEqual, true)
patch.Reset()
fmt.Println("CompareInt test success")
}
————————————————
版权声明:本文为CSDN博主「jiuweiC」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/jiuweiC/article/details/110442937
----------------
gomonkey 介绍
gomonkey 是 golang 的一款打桩框架,目标是让用户在单元测试中低成本的完成打桩,从而将精力聚焦于业务功能的开发。gomonkey 接口友好,功能强大,目前已被很多项目使用,用户遍及世界多个国家。
gomonkey 1.0 特性列表
gomonkey 1.0 特性列表如下:
- 支持为一个函数打一个桩
- 支持为一个成员方法打一个桩
- 支持为一个全局变量打一个桩
- 支持为一个函数变量打一个桩
- 支持为一个函数打一个特定的桩序列
- 支持为一个成员方法打一个特定的桩序列
- 支持为一个函数变量打一个特定的桩序列
下载地址:
https://github.com/agiledragon/gomonkey/releases/tag/v1.0
习惯用法
gomonkey 提供的 API 包括函数接口和成员方法接口,接口契约一致,扩展性很强。
示例代码中用到了 goconvey,它是一款针对 golang 的测试框架,可以管理和运行测试用例,同时提供了丰富的断言函数,并支持很多 Web 界面特性。
ApplyFunc
ApplyFunc 接口定义如下:
func ApplyFunc(target, double interface{}) *Patches func (this *Patches) ApplyFunc(target, double interface{}) *Patches
ApplyFunc 第一个参数是函数名,第二个参数是桩函数。测试完成后,patches 对象通过 Reset 成员方法删除所有测试桩。
函数打桩的习惯用法:
import ( . "github.com/agiledragon/gomonkey" . "github.com/smartystreets/goconvey/convey" "testing" "github.com/agiledragon/gomonkey/test/fake" "encoding/json" ) var ( outputExpect = "xxx-vethName100-yyy" ) func TestApplyFunc(t *testing.T) { Convey("TestApplyFunc", t, func() { Convey("one func for succ", func() { patches := ApplyFunc(fake.Exec, func(_ string, _ ...string) (string, error) { return outputExpect, nil }) defer patches.Reset() output, err := fake.Exec("", "") So(err, ShouldEqual, nil) So(output, ShouldEqual, outputExpect) }) Convey("one func for fail", func() { patches := ApplyFunc(fake.Exec, func(_ string, _ ...string) (string, error) { return "", fake.ErrActual }) defer patches.Reset() output, err := fake.Exec("", "") So(err, ShouldEqual, fake.ErrActual) So(output, ShouldEqual, "") }) Convey("two funcs", func() { patches := ApplyFunc(fake.Exec, func(_ string, _ ...string) (string, error) { return outputExpect, nil }) defer patches.Reset() patches.ApplyFunc(fake.Belong, func(_ string, _ []string) bool { return true }) output, err := fake.Exec("", "") So(err, ShouldEqual, nil) So(output, ShouldEqual, outputExpect) flag := fake.Belong("", nil) So(flag, ShouldBeTrue) 