当前位置:网站首页>Use gomonkey mock function and method
Use gomonkey mock function and method
2022-06-22 01:30:00 【CG Guobin】
List of articles
Preface
stay Golang In language , When writing unit tests , Inevitably, it will involve the modification of other functions and methods Mock, That is, while assuming that other functions and methods respond to the expected results , Verify whether the response of the function under test meets the expectation .
among , stay Mock Other functions and methods , A common test class library we use is 「gomonkey」. Specially , For methods and functions Mock, Slightly different , Here we give functions and methods respectively Mock Example , For your reference .
function
stay Golang In language , A function is a method that has no receiver , In the form of
func function_name([parameter list]) [return_types] {
The body of the function
}
For function Mock Relatively simple , Suppose we are right A Function to unit test , And A Function called again B function , for example
func A(ctx context.Context, str string) error {
if len(str) == 0 {
return errors.New("str is empty")
}
return test_package_name.B(ctx, str)
}
In order to A Each line of the function covers , The unit test can be written as :
func TestA(t *testing.T) {
type args struct {
ctx context.Context
str string
}
tests := []struct {
name string
args args
Setup func(t *testing.T)
wantErr error
}{
{
name: "len(str) == 0",
wantErr: errors.New("str is empty")
},
{
name: " Normal response ",
Setup: func(t *testing.T) {
patches := gomonkey.ApplyFunc(test_package_name.B, func(_ context.Context, _ string) error {
return nil
})
t.Cleanup(func() {
patches.Reset()
})
},
args: args{
ctx: context.Background(),
str: "test",
},
wantErr: nil,
},
}
// Execute test case
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.Setup != nil {
tt.Setup(t)
}
err := A(tt.args.ctx, tt.args.str)
if err != nil {
assert.EqualError(t, err, tt.wantErr.Error(), "error Fall short of expectations ")
}
})
}
}
among ,ApplyFunc The function is used to Mock Functional , The first parameter is required Mock The function name of ( There is no need to write parameter list ), The second parameter is required Mock Function result of ; Specially , stay Setup Inside , We need to remember to explicitly call Cleanup Yes patches Conduct Reset operation , Prevent the Mock Affect other test cases .
Method
stay Golang In language , The method is a function that contains the receiver , In the form of
func (variable_name variable_data_type) function_name([parameter list]) [return_type]{
The body of the function
}
For method Mock It's relatively complicated , Suppose we are right A Function to unit test , And A The structure is called in the function C Of B Method , for example
func A(ctx context.Context, str string) error {
if len(str) == 0 {
return errors.New("str is empty")
}
c := &test_package_name.C{
}
return c.B(ctx, str)
}
In order to A Each line of the function covers , The unit test can be written as :
func TestA(t *testing.T) {
// initialization C structure
var c *test_package_name.C
type args struct {
ctx context.Context
str string
}
tests := []struct {
name string
args args
Setup func(t *testing.T)
wantErr error
}{
{
name: "len(str) == 0",
wantErr: errors.New("str is empty")
},
{
name: " Normal response ",
Setup: func(t *testing.T) {
patches := gomonkey.ApplyMethod(reflect.TypeOf(c), "B", func(_ *test_package_name.C, _ context.Context, _ string) error {
return nil
})
t.Cleanup(func() {
patches.Reset()
})
},
args: args{
ctx: context.Background(),
str: "test",
},
wantErr: nil,
},
}
// Execute test case
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.Setup != nil {
tt.Setup(t)
}
err := A(tt.args.ctx, tt.args.str)
if err != nil {
assert.EqualError(t, err, tt.wantErr.Error(), "error Fall short of expectations ")
}
})
}
}
among ,ApplyMethod The function is used to Mock Methodical , The first parameter is required Mock The recipient type of the method of , The second parameter is required Mock Method name of ( String type ), The third parameter is required Mock The definition and Mock result ; Specially , The first and third parameters require our attention :
- The first parameter , Need to use
reflect.TypeOfGet the type of recipient , The initialized recipient must be a real type , Such as structure C Combined structure D, andBThe method is to combine D Got , You need to define the structure during initialization D, Not the structure C, Otherwise, null pointer exception will be reported ; - The third parameter , although
BThe method declaration isfunc(ctx context.Context, str string), But in useApplyMethodWhen , Need to putBThe declaration of the method is modified tofunc(c *test_package_name.C, ctx context.Context, str string), That is, you need to set the receiver of the method as the first parameter of the method .
Reference resources
And that is , We are using gomonkey When , You may encounter the problem of permission verification and non - Debug The problem that the mode fails to run , You can refer to :
- golang Use gomonkey and monkey Come on mock Method or function times panic: permission denied
- Use gomonkey Encounter non debug The problem of pattern execution failure and its solution
Come here , This is the end of the article , I hope that's helpful .
边栏推荐
- LeetCode 5242. 兼具大小写的最好英文字母
- 【ÑÖÏ模拟赛】花萎(矩阵加速,循环卷积,高斯消元)
- 站在数字化风口,工装企业如何“飞起来”
- SQL操作:WITH表达式及其应用
- Virtual variables and formatting characters in debugging
- 想加入大厂?看这篇文章也许会帮助到你
- English语法_副词 - loud /aloud / loudly
- 经费预算与调整记录与使用记录输出使用进度搭建过程记录
- HDOJ - Is It A Tree?
- I just learned a cool 3D pyramid stereoscopic effect. Come and have a look
猜你喜欢

SSO and oauth2 solutions

记录webscraper的使用过程

How to remove duplication in left join from a simple example

消息队列之发送 Webhook 实现跨应用异步回调

Compilation principle - recursive descent subroutine method

SAP MM 进口采购业务中供应商多送或者少送场景的处理

Pytorch learning 12: automatic derivation

Making unequal interval histogram with Matplotlib
![[redis] event driven framework source code analysis (single thread)](/img/72/ae961423832f217324007c81b6f9e5.png)
[redis] event driven framework source code analysis (single thread)

Some introduction and transplantation of lvgl
随机推荐
crf*.bdb文件过大问题处理
3746. 牛的学术圈 II
Precautions for using timestamp type of SQLite3 database
Difference between integer and int
Tables and table structures related to the flowable runtime transaction
Documenter l'utilisation de webcraper
php-admin部署-解决全部错误
What does container cloud mean? What is the difference with fortress machine?
Gaode map -- obtain longitude and latitude according to geographical location
LCP 17. 速算机器人
[cyw20189] VII. Detailed explanation of HCI command format
BigDecimal basic use
Using SSM framework to realize user login
Dynamic programming-01 backpack, partition, etc. and subset, weight of the last stone
Brief description of advantages and disadvantages of cloud fortress distributed cluster deployment
Navicat连接不到MySQL
Today's content
==和equals的区别
MySQL 8.0 新特性梳理汇总
3371. comfortable cow