go语言中的GoMock

2024-01-16 09:36
文章标签 语言 go gomock

本文主要是介绍go语言中的GoMock,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

GoMock是一个Go框架。它与内置的测试包整合得很好,并在单元测试时提供了灵活性。正如我们所知,对具有外部资源(数据库、网络和文件)或依赖关系的代码进行单元测试总是很麻烦。

安装

为了使用GoMock,我们需要安装gomock包github.com/golang/mock/gomock和mockgen代码生成工具github.com/golang/mock/mockgen。使用这个命令行:

go get github.com/golang/mock/gomock
go get github.com/golang/mock/mockgen

GoMock的使用遵循四个基本步骤:

  • 使用mockgen为你想模拟的接口生成一个模拟对象。
  • 在测试部分,创建一个gomock.Controller的实例,并把它传递给你的mock对象的构造函数以获得一个mock对象。
  • 在mock上调用EXPECT()来设置期望值和返回值。
  • 在模拟控制器上调用Finish()来断言模拟对象的期望。

开始

让我们创建一个这样的文件夹(本代码在 go1.16.15 版本下执行)

gomock_test
├── doer
│ └── doer.go
├── mocks
│ └── mock_doer.go
└── user├── user.go└── user_test.go

doer/doer.go

package doertype Doer interface {DoSomething(int, string) errorSaySomething(string) string
}

那么这里是我们在模拟Doer接口时要测试的代码。

user/user.go

package userimport "gomock_test/doer"const (filtered   = "OK"unfiltered = "spam"Nice       = "nice"Bad        = "bad"
)type User struct {// struct while mocking the doer interfaceDoer doer.Doer
}// method Use using it
func (u *User) Use() error {return u.Doer.DoSomething(123, "Hello GoMock")
}func (u *User) SaySomething(num int) string {if num == 3 {return u.Doer.SaySomething(unfiltered)}return u.Doer.SaySomething(filtered)
}type Student struct{}func (s *Student) DoSomething(_ int, _ string) error {panic("not implemented") // TODO: Implement
}func (s *Student) SaySomething(kata string) string {if kata == filtered {return Nice}return Bad
}

我们将把Doer的模拟放在一个包mocks中。我们首先创建一个包含我们的模拟实现的目录mocks,然后在doer包上运行mockgen:

mockgen -destination=../mocks/mock_doer.go -package=mocks gomock_test/doer Doer

NOTE: 在执行这步的时候,会报错:Failed to format generated source code: mocks/mock_doer.go:5:15: expected ‘;’, found '.’ 这个时候,我们只需要将打印出来的代码复制到我们对应的文件中即可。

当有大量的接口/包需要模拟时,为每个包和接口运行mockgen是一种乌托邦。为了缓解这个问题,可以将mockgen命令与go:generate放在一起。

go:generate mockgen -destination=../mocks/mock_doer.go -package=mocks gomock_test/doer Doer

我们必须自己创建目录模拟,因为GoMock不会为我们这样做,而是会以错误退出。

  • destination=…/mocks/mock_doer.go : 把生成的mocks放在这个路径下。
  • -package=mocks : 把生成的mocks放在这个包里
  • gomock_test/doer : 为这个包生成mocks。
  • Doer : 为这个接口生成mocks(必填),因为我们需要指定哪个接口来生成mocks。(如果需要的话,可以用逗号分隔的列表来指定多个接口。例如,Doer1, Doer2)

因为我们对mockgen的调用在我们的项目中放置了一个文件mocks/mock_doer.go。这就是这样一个生成的mock实现的样子:

// Code generated by MockGen. DO NOT EDIT.
// Source: github.com/timliudream/go-test/gomock_test/doer (interfaces: Doer)// Package github.com/timliudream/go-test/gomock_test/mocks is a generated GoMock package.
package mocksimport (gomock "github.com/golang/mock/gomock"reflect "reflect"
)// MockDoer is a mock of Doer interface.
type MockDoer struct {ctrl     *gomock.Controllerrecorder *MockDoerMockRecorder
}// MockDoerMockRecorder is the mock recorder for MockDoer.
type MockDoerMockRecorder struct {mock *MockDoer
}// NewMockDoer creates a new mock instance.
func NewMockDoer(ctrl *gomock.Controller) *MockDoer {mock := &MockDoer{ctrl: ctrl}mock.recorder = &MockDoerMockRecorder{mock}return mock
}// EXPECT returns an object that allows the caller to indicate expected use.
func (m *MockDoer) EXPECT() *MockDoerMockRecorder {return m.recorder
}// DoSomething mocks base method.
func (m *MockDoer) DoSomething(arg0 int, arg1 string) error {m.ctrl.T.Helper()ret := m.ctrl.Call(m, "DoSomething", arg0, arg1)ret0, _ := ret[0].(error)return ret0
}// DoSomething indicates an expected call of DoSomething.
func (mr *MockDoerMockRecorder) DoSomething(arg0, arg1 interface{}) *gomock.Call {mr.mock.ctrl.T.Helper()return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoSomething", reflect.TypeOf((*MockDoer)(nil).DoSomething), arg0, arg1)
}// SaySomething mocks base method.
func (m *MockDoer) SaySomething(arg0 string) string {m.ctrl.T.Helper()ret := m.ctrl.Call(m, "SaySomething", arg0)ret0, _ := ret[0].(string)return ret0
}// SaySomething indicates an expected call of SaySomething.
func (mr *MockDoerMockRecorder) SaySomething(arg0 interface{}) *gomock.Call {mr.mock.ctrl.T.Helper()return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SaySomething", reflect.TypeOf((*MockDoer)(nil).SaySomething), arg0)
}

接下来,我们在测试中定义一个模拟控制器。一个模拟控制器负责跟踪和断言其相关模拟对象的期望。我们可以通过传递一个*testing.T类型的值给它的构造函数来获得一个模拟控制器,并使用它来构造一个Doer接口的模拟对象。

//core of gomock
mockCtrl := gomock.NewController(t)
//used to trigger final assertions. if its ignored, mocking assertions will never fail
defer mockCtrl.Finish()
// create a new mock object, passing the controller instance as parameter
// for a newly created mock object it will accept any input and outpuite
// need to define its behavior with the method expect
mockDoer := mocks.NewMockDoer(mockCtrl)

使用参数匹配器

在GoMock中,一个参数可以被期望有一个固定的值,也可以被期望与一个谓词(称为匹配器)相匹配。匹配器用于表示被模拟方法的预期参数范围。下列匹配器在Gomock中被预先定义了:

  • gomock.Any() : 匹配任何值(任何类型)。
  • gomock.Eq(x) : 使用反射来匹配与x深度相等的值。
  • gomock.Nil() : 匹配nil

user/user_test.go

package userimport ("fmt""github.com/golang/mock/gomock""gomock_test/mocks""testing"
)func TestUse(t *testing.T) {//core of gomockmockCtrl := gomock.NewController(t)//used to trigger final assertions. if its ignored, mocking assertions will never faildefer mockCtrl.Finish()// create a new mock object, passing the controller instance as parameter// for a newly created mock object it will accept any input and outpuite// need to define its behavior with the method expectmockDoer := mocks.NewMockDoer(mockCtrl)testUser := &User{Doer: mockDoer}//// Expect Do to be called once with 123 and "Hello GoMock" as parameters, and return nil from the mocked call.mockDoer.EXPECT().DoSomething(123, "Hello GoMock").Return(nil).Times(1)fmt.Println(testUser.Use())fmt.Println()
}func TestUser_SaySomething(t *testing.T) {mockCtrl := gomock.NewController(t)defer mockCtrl.Finish()mockDoer := mocks.NewMockDoer(mockCtrl)user := User{Doer: mockDoer,}type args struct {num int}tests := []struct {name    stringargs    argswant    stringexpect  func()wantErr bool}{{name: "Positive test case 1",expect: func() {mockDoer.EXPECT().SaySomething("spam").Return("bad")},args:    args{num: 3},wantErr: false,want:    "bad",},}for _, tt := range tests {t.Run(tt.name, func(t *testing.T) {tt.expect()if got := user.SaySomething(tt.args.num); (got != tt.want) != tt.wantErr {fmt.Println("gott :", got)t.Errorf("User.SaySomething() = %v, want %v", got, tt.want)}})}
}

而单元测试的结果将是这样的:

=== RUN   TestUser_SaySomething
=== RUN   TestUser_SaySomething/Positive_test_case_1
--- PASS: TestUser_SaySomething (0.00s)--- PASS: TestUser_SaySomething/Positive_test_case_1 (0.00s)
PASS
ok      github.com/tokopedia/go_learning/udemy/pzn/gomock_test/user     1.100s

这篇关于go语言中的GoMock的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/612117

相关文章

go 指针接收者和值接收者的区别小结

《go指针接收者和值接收者的区别小结》在Go语言中,值接收者和指针接收者是方法定义中的两种接收者类型,本文主要介绍了go指针接收者和值接收者的区别小结,文中通过示例代码介绍的非常详细,需要的朋友们下... 目录go 指针接收者和值接收者的区别易错点辨析go 指针接收者和值接收者的区别指针接收者和值接收者的

Go 语言中的select语句详解及工作原理

《Go语言中的select语句详解及工作原理》在Go语言中,select语句是用于处理多个通道(channel)操作的一种控制结构,它类似于switch语句,本文给大家介绍Go语言中的select语... 目录Go 语言中的 select 是做什么的基本功能语法工作原理示例示例 1:监听多个通道示例 2:带

C语言函数递归实际应用举例详解

《C语言函数递归实际应用举例详解》程序调用自身的编程技巧称为递归,递归做为一种算法在程序设计语言中广泛应用,:本文主要介绍C语言函数递归实际应用举例的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录前言一、递归的概念与思想二、递归的限制条件 三、递归的实际应用举例(一)求 n 的阶乘(二)顺序打印

Go标准库常见错误分析和解决办法

《Go标准库常见错误分析和解决办法》Go语言的标准库为开发者提供了丰富且高效的工具,涵盖了从网络编程到文件操作等各个方面,然而,标准库虽好,使用不当却可能适得其反,正所谓工欲善其事,必先利其器,本文将... 目录1. 使用了错误的time.Duration2. time.After导致的内存泄漏3. jsO

go中空接口的具体使用

《go中空接口的具体使用》空接口是一种特殊的接口类型,它不包含任何方法,本文主要介绍了go中空接口的具体使用,具有一定的参考价值,感兴趣的可以了解一下... 目录接口-空接口1. 什么是空接口?2. 如何使用空接口?第一,第二,第三,3. 空接口几个要注意的坑坑1:坑2:坑3:接口-空接口1. 什么是空接

C语言中的数据类型强制转换

《C语言中的数据类型强制转换》:本文主要介绍C语言中的数据类型强制转换方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录C语言数据类型强制转换自动转换强制转换类型总结C语言数据类型强制转换强制类型转换:是通过类型转换运算来实现的,主要的数据类型转换分为自动转换

利用Go语言开发文件操作工具轻松处理所有文件

《利用Go语言开发文件操作工具轻松处理所有文件》在后端开发中,文件操作是一个非常常见但又容易出错的场景,本文小编要向大家介绍一个强大的Go语言文件操作工具库,它能帮你轻松处理各种文件操作场景... 目录为什么需要这个工具?核心功能详解1. 文件/目录存javascript在性检查2. 批量创建目录3. 文件

C语言实现两个变量值交换的三种方式

《C语言实现两个变量值交换的三种方式》两个变量值的交换是编程中最常见的问题之一,以下将介绍三种变量的交换方式,其中第一种方式是最常用也是最实用的,后两种方式一般只在特殊限制下使用,需要的朋友可以参考下... 目录1.使用临时变量(推荐)2.相加和相减的方式(值较大时可能丢失数据)3.按位异或运算1.使用临时

使用C语言实现交换整数的奇数位和偶数位

《使用C语言实现交换整数的奇数位和偶数位》在C语言中,要交换一个整数的二进制位中的奇数位和偶数位,重点需要理解位操作,当我们谈论二进制位的奇数位和偶数位时,我们是指从右到左数的位置,本文给大家介绍了使... 目录一、问题描述二、解决思路三、函数实现四、宏实现五、总结一、问题描述使用C语言代码实现:将一个整

C语言字符函数和字符串函数示例详解

《C语言字符函数和字符串函数示例详解》本文详细介绍了C语言中字符分类函数、字符转换函数及字符串操作函数的使用方法,并通过示例代码展示了如何实现这些功能,通过这些内容,读者可以深入理解并掌握C语言中的字... 目录一、字符分类函数二、字符转换函数三、strlen的使用和模拟实现3.1strlen函数3.2st