ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

go语言单元测试:go语言用gomonkey为测试函数或方法打桩

2022-06-09 22:01:54  阅读:199  来源: 互联网

标签:语言 int MyUser patch func 测试函数 go model


一,安装用到的库
1,gomonkey代码的地址:

https://github.com/agiledragon/gomonkey

2,从命令行安装gomonkey

go get -u github.com/agiledragon/gomonkey
3,goconvey库的代码地址

https://github.com/smartystreets/goconvey

4,从命令行安装

go get -u github.com/smartystreets/goconvey

二,演示项目的相关信息
功能说明:演示了使用gomonkey库在项目中测试时打桩

三,go代码说明
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"

否则打桩可能不会生效

返回:  

标签:语言,int,MyUser,patch,func,测试函数,go,model
来源: https://www.cnblogs.com/gongxianjin/p/16361338.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有