77 lines
1.5 KiB
Markdown
77 lines
1.5 KiB
Markdown
### 方法 mock
|
|
```go
|
|
var cMock *PassService
|
|
passSer := gomonkey.ApplyMethod(reflect.TypeOf(cMock), "PassUidToUnionId",
|
|
func(_ *PassService, userId uint64) (string, error) {
|
|
return "test", nil
|
|
})
|
|
defer passSer.Reset()
|
|
```
|
|
|
|
```go
|
|
func (t *PassService) PassUidToUnionId(userId uint64)(string, error){
|
|
// 函数逻辑
|
|
return ret.Encoding.UnionID, nil
|
|
}
|
|
```
|
|
|
|
### 函数 mock
|
|
```go
|
|
func function_name([parameter list]) [return_types] {
|
|
函数体
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
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: "正常响应",
|
|
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,
|
|
},
|
|
}
|
|
|
|
// 执行测试用例
|
|
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 不符合预期")
|
|
}
|
|
})
|
|
}
|
|
}
|
|
``` |