xgo 使用经验

Patch

mock 函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func greet(s string) string {
return "hello " + s
}

func TestPatchFunc(t *testing.T) {
mock.Patch(greet, func(s string) string {
return "mock " + s
})

res := greet("world")
if res != "mock world" {
t.Fatalf("expteced mock world got %s", res)
}
}

mock 变量

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var value = "hello"

func greet(s string) string {
return value + s
}

func TestPatchVar(t *testing.T) {
mock.Patch(&value, func() string {
return "mock "
})
res := greet("world")
if res != "mock world" {
t.Fatalf("expteced mock world got %s", res)
}
}

func TestPatchVarByName(t *testing.T) {
mock.PatchByName("learn-xgo/api", "value", func() string {
return "mock "
})
res := greet2("world")
if res != "mock world" {
t.Fatalf("expteced mock world got %s", res)
}
}

Mock

因此,当函数含有未导出类型时,Patch 无法使用,此时可以使用 Mock

MockByName

1
2
3
4
5
6
7
8
9
10
// learn-xgo/funcs/funcs.go
package funcs

func CallUnexportedFunc(s string) string {
return unexportedFunc(s)
}

func unexportedFunc(s string) string {
return "origin unexported func, your msg is " + s
}
1
2
3
4
5
6
7
8
9
10
11
12
13
// learn-xgo/api/mock_test.go
func TestMockByName(t *testing.T) {
mock.MockByName("learn-xgo/funcs", "unexportedFunc",
func(ctx context.Context, fn *core.FuncInfo, args core.Object, results core.Object) error {
results.GetFieldIndex(0).Set("mock funcs " + args.GetFieldIndex(0).Value().(string))
return nil
})

msg := funcs.CallUnexportedFunc("hedon")
if msg != "mock funcs hedon" {
t.Fatalf("expteced `mock funcs hedon` got %s", msg)
}
}

xgo 使用经验
https://hedon.top/2024/05/21/go-xgo-use/
Author
Hedon Wang
Posted on
2024-05-21
Licensed under