1 回答

TA貢獻(xiàn)1786條經(jīng)驗(yàn) 獲得超11個(gè)贊
根據(jù)您的問題,我假設(shè)您正在使用github.com/olivere/elastic,并且您希望能夠使用存根 http 響應(yīng)進(jìn)行測試。當(dāng)我第一次閱讀這個(gè)問題時(shí),我也從未編寫過使用 ES 客戶端的 Go 測試代碼。所以,除了回答這個(gè)問題,我還分享了我是如何從 godocs 中找到答案的。
首先,我們可以看到elastic.NewClient接受客戶端選項(xiàng)功能。所以我檢查了庫提供了什么樣的客戶端選項(xiàng)功能。原來圖書館提供elastic.SetHttpClient了接受elastic.Doer. Doer是一個(gè)http.Client可以實(shí)現(xiàn)的接口。從這里,答案變得清晰。
所以,你必須:
將您的更改func NewESSink()為接受 http 客戶端或彈性客戶端。
編寫存根 http 客戶端(實(shí)現(xiàn)elastic.Doer)。
ESSink
type ESSink struct {
client *elastic.Client
}
func NewESSink(client *elastic.Client) *ESSink {
return &ESSink{client: client}
}
存根 HttpClient
package stubs
import "net/http"
type HTTPClient struct {
Response *http.Response
Error error
}
func (c *HTTPClient) Do(*http.Request) (*http.Response, error) {
return c.Response, c.Error
}
你的測試代碼
func TestWrite(t *testing.T) {
// set the body and error according to your test case
stubHttpClient := stubs.HTTPClient{
Response: &http.Response{Body: ...},
Error: ...,
}
elasticClient := elastic.NewClient(elastic.SetHttpClient(stubHttpClient))
esSink := NewESSink(elasticClient)
esSink.Write(...)
}
在您的生產(chǎn)代碼中,您可以http.Client{}在設(shè)置 ES http 客戶端時(shí)使用。
- 1 回答
- 0 關(guān)注
- 142 瀏覽
添加回答
舉報(bào)