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 關注
- 106 瀏覽
添加回答
舉報