What is piling?
The term piling may have been borrowed from the construction industry to refer to wooden or steel piles driven into the ground with a hammer or machine to form the foundation of a building.
Simply speaking, piling is to replace some code segments, which are "stubs". The main thing that can be done in GoStub is piling a global variable, piling a function, and piling a process.
Guide package
go get github.com/prashantv/gostub
The difference between stub and mock
Mock: It means simulation, which refers to creating a structure in the test package to satisfy an externally dependent interface interface{}.
Stub: It means a pile, which refers to creating a mock method in the test package to replace the method in the generated code.
go stub example
1. Pile variables
var num int = 10
func JudgeNum() bool {
return num >= 100
}
func TestStub(t *testing.T) {
convey.Convey("start", t, func() {
stub := gostub.Stub(&num, 150) //对num打桩,将num的值替代为150
defer stub.Reset() //对所有桩上的变量进行重置
convey.So(JudgeNum(), convey.ShouldBeTrue)
stub.Stub(&num, 80)
convey.So(JudgeNum(), convey.ShouldBeTrue) //报错,JudgeNum()返回了false
})
}
2. Pile the function
var num int = 10
func JudgeNum() bool {
return num >= 100
}
var fc = JudgeNum
func TestStub(t *testing.T) {
convey.Convey("start", t, func() {
stub := gostub.StubFunc(&fc, true)//fc为桩,返回true
defer stub.Reset()
convey.So(fc(), convey.ShouldBeFalse) //报错
})
You can see that convey.So reported an error, fc() should return false without piling, but now the return value is true.
3. Pile the process
A procedure is a function that does not return a value and performs some work (such as resource cleanup).
//清理函数
func Clear() {
fmt.Println("do clear()")
}
var clear = Clear
func TestStub(t *testing.T) {
convey.Convey("start", t, func() {
stub := gostub.StubFunc(&clear) //对clear函数进行打桩,无返回值
defer stub.Reset()
clear()//调用clear()
})
Result: clear() does not print output, indicating that clear has been replaced by a procedure (stub) that does not return a value.
Reference: https://zhuanlan.zhihu.com/p/168539526