亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何對與 Elasticsearch 交互的 go 代碼進行單元測試

如何對與 Elasticsearch 交互的 go 代碼進行單元測試

Go
拉風的咖菲貓 2022-05-23 14:51:46
我有一個應用程序,它定義了一個type Client struct {}在我的代碼中與其他各種客戶端對話的應用程序,這些客戶端與 github、elasticsearch 等服務對話?,F在我的一個包中有以下 ES 代碼type SinkService interface {    Write(context, index, mapping, doc)}type ESSink struct {   client *elastic.Client}func NewESSink() *ESSink {} // checks if the index exists and writes the docfunc (s *ESSink) Write(context, index, mapping, doc) {}我在像這樣運行整個應用程序的主客戶端中使用此方法c.es.Write(...)?,F在,如果我想編寫client_test.go,我可以簡單地制作一個 mockESSink 并將它與一些存根代碼一起使用,但這不會涵蓋我的 ES 代碼中編寫的行。如何對我的 ES 代碼進行單元測試?我的 ESSink 使用elastic.Client. 我如何嘲笑它?我想嵌入一些模擬 ES 客戶端,它給我存根響應,我將能夠以這種方式測試我ESSink.Write的方法。
查看完整描述

1 回答

?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

根據您的問題,我假設您正在使用github.com/olivere/elastic,并且您希望能夠使用存根 http 響應進行測試。當我第一次閱讀這個問題時,我也從未編寫過使用 ES 客戶端的 Go 測試代碼。所以,除了回答這個問題,我還分享了我是如何從 godocs 中找到答案的。


首先,我們可以看到elastic.NewClient接受客戶端選項功能。所以我檢查了庫提供了什么樣的客戶端選項功能。原來圖書館提供elastic.SetHttpClient了接受elastic.Doer. Doer是一個http.Client可以實現的接口。從這里,答案變得清晰。


所以,你必須:


將您的更改func NewESSink()為接受 http 客戶端或彈性客戶端。

編寫存根 http 客戶端(實現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(...)

}

在您的生產代碼中,您可以http.Client{}在設置 ES http 客戶端時使用。


查看完整回答
反對 回復 2022-05-23
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號