1 回答
TA貢獻1825條經驗 獲得超4個贊
可測試代碼的一個非?;镜囊巹t是,您不能只在其他服務中創建新服務。您需要注入它,并準備一個接口(如果返回的內容還沒有接口的話)resty.New。這樣你就可以在測試中注入你的模擬。
然后你可以使用例如https://pkg.go.dev/github.com/stretchr/testify/mock來生成模擬并說明你的模擬服務應該返回什么值。
評論后更新:
type HttpClient struct {
logger *logger.Logger
config *config.Server
instrumentation *instrumentation
record *logger.LogRecord
restyClient *resty.Client // <- this is the thing you want to change from a pointer to resty.Client to an interface
}
檢查restyClient您在代碼中使用了哪些方法,并創建包含它們的新接口,例如:
type MyRestyClient interface {
FirstUsedMethod(..)
...
}
并將 restyClient 聲明交換為
type HttpClient struct {
...
restyClient MyRestyClient
之后,您可以使用我之前粘貼的鏈接中的模擬和命令為您生成模擬。
稍后,您只需在測試中設置模擬:
restyMock := new(RestyMock)
restyMock.On("MethodYouExpect").Return(returnValueOfYourChoice)
然后您將準備好的模擬注入到您的測試服務中。
- 1 回答
- 0 關注
- 131 瀏覽
添加回答
舉報
