go語言monkey庫,進行mock
1、目的
模塊自測,對依賴的模塊函數進行mock,從而達到不更改其他模塊代碼,完成本模塊全部代碼測試的目的
2、庫:https://github.com/bouk/monkey
3、函數以及方法舉例
目錄結構
src
test
24_mock
main
main.go
mock_test
mock.go
test
test.go
運行結果:
a:1+b:2=3
a:1+b:2
a:1+b:2=3
a:1+b:2
Process finished with exit code 0
代碼如下:
main.go
package main
import (
"github.com/bouk/monkey"
"test/24_mock/test"
"test/24_mock/mock_test"
"fmt"
"reflect"
)
func test1() {
monkey.Patch(test.PrintAdd, mock_test.PrintAdd)
p := test.PrintAdd(1, 2)
fmt.Println(p)
monkey.UnpatchAll() //解除所有替換
p = test.PrintAdd(1, 2)
fmt.Println(p)
}
func test2() {
structSum := &test.SumTest{}
//para1:獲取實例的反射類型,para2:被替換的方法名,para3:替換方法
monkey.PatchInstanceMethod(reflect.TypeOf(structSum), "PrintSum", mock_test.PrintSum)
p := structSum.PrintSum(1, 2)
fmt.Println(p)
monkey.UnpatchAll() //解除所有替換
p = structSum.PrintSum(1, 2)
fmt.Println(p)
}
func main() {
test1()
test2()
}
mock.go
package mock_test
import "fmt"
import "test/24_mock/test"
func PrintAdd(a, b uint32) string {
return fmt.Sprintf("a:%v+b:%v=%v", a, b, a+b)
}
//對應test文件夾下的PrintSum
func PrintSum(_ *test.SumTest, a, b uint32) string {
return fmt.Sprintf("a:%v+b:%v=%v", a, b,a+b)
}
test.go
package test
import "fmt"
func PrintAdd(a, b uint32) string {
return fmt.Sprintf("a:%v+b:%v", a, b)
}
type SumTest struct {
}
func (*SumTest)PrintSum(a, b uint32) string {
return fmt.Sprintf("a:%v+b:%v", a, b)
}