1 回答
TA贡献1852条经验 获得超1个赞
我会从一个界面开始:
type ClientProvider interface {
GetClient(token string, url string) (*github.Client, context.Context, error)
}
测试需要调用的单元时,请确保依赖于接口:GetClientClientProvider
func YourFunctionThatNeedsAClient(clientProvider ClientProvider) error {
// build you token and url
// get a github client
client, ctx, err := clientProvider.GetClient(token, url)
// do stuff with the client
return nil
}
现在,在您的测试中,您可以构造如下存根:
// A mock/stub client provider, set the client func in your test to mock the behavior
type MockClientProvider struct {
GetClientFunc func(string, string) (*github.Client, context.Context, error)
}
// This will establish for the compiler that MockClientProvider can be used as the interface you created
func (provider *MockClientProvider) GetClient(token string, url string) (*github.Client, context.Context, error) {
return provider.GetClientFunc(token, url)
}
// Your unit test
func TestYourFunctionThatNeedsAClient(t *testing.T) {
mockGetClientFunc := func(token string, url string) (*github.Client, context.Context, error) {
// do your setup here
return nil, nil, nil // return something better than this
}
mockClientProvider := &MockClientProvider{GetClientFunc: mockGetClientFunc}
// Run your test
err := YourFunctionThatNeedsAClient(mockClientProvider)
// Assert your result
}
这些想法不是我自己的,我从我之前的人那里借来的。Mat Ryer在一个关于“惯用语golang”的精彩视频中提出了这个(和其他想法)。
如果要存根 github 客户端本身,可以使用类似的方法(如果是 github)。客户端是一个结构,你可以用一个接口来隐藏它。如果它已经是一个接口,则上述方法直接起作用。
- 1 回答
- 0 关注
- 149 浏览
添加回答
举报
