1 回答

TA貢獻(xiàn)1825條經(jīng)驗(yàn) 獲得超4個(gè)贊
可測(cè)試代碼的一個(gè)非?;镜囊?guī)則是,您不能只在其他服務(wù)中創(chuàng)建新服務(wù)。您需要注入它,并準(zhǔn)備一個(gè)接口(如果返回的內(nèi)容還沒(méi)有接口的話)resty.New。這樣你就可以在測(cè)試中注入你的模擬。
然后你可以使用例如https://pkg.go.dev/github.com/stretchr/testify/mock來(lái)生成模擬并說(shuō)明你的模擬服務(wù)應(yīng)該返回什么值。
評(píng)論后更新:
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您在代碼中使用了哪些方法,并創(chuàng)建包含它們的新接口,例如:
type MyRestyClient interface {
FirstUsedMethod(..)
...
}
并將 restyClient 聲明交換為
type HttpClient struct {
...
restyClient MyRestyClient
之后,您可以使用我之前粘貼的鏈接中的模擬和命令為您生成模擬。
稍后,您只需在測(cè)試中設(shè)置模擬:
restyMock := new(RestyMock)
restyMock.On("MethodYouExpect").Return(returnValueOfYourChoice)
然后您將準(zhǔn)備好的模擬注入到您的測(cè)試服務(wù)中。
- 1 回答
- 0 關(guān)注
- 114 瀏覽
添加回答
舉報(bào)