1 回答

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
我會(huì)從一個(gè)界面開始:
type ClientProvider interface {
GetClient(token string, url string) (*github.Client, context.Context, error)
}
測試需要調(diào)用的單元時(shí),請確保依賴于接口: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
}
現(xiàn)在,在您的測試中,您可以構(gòu)造如下存根:
// 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在一個(gè)關(guān)于“慣用語golang”的精彩視頻中提出了這個(gè)(和其他想法)。
如果要存根 github 客戶端本身,可以使用類似的方法(如果是 github)??蛻舳耸且粋€(gè)結(jié)構(gòu),你可以用一個(gè)接口來隱藏它。如果它已經(jīng)是一個(gè)接口,則上述方法直接起作用。
- 1 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)