[英]How does one unit test code that interacts with the Core Bluetooth APIs?
[英]How to unit test go code that interacts with Elasticsearch
我有一個應用程序,它定義了一個type Client struct {}
,它與我的代碼中的各種其他客戶端進行對話,這些客戶端與 github、elasticsearch 等服務對話。
現在我的一個包中有以下 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 doc
func (s *ESSink) Write(context, index, mapping, doc) {}
我在像c.es.Write(...)
一樣運行整個應用程序的主客戶端中使用此方法。 現在,如果我想編寫client_test.go
我可以簡單地制作一個 mockESSink 並將其與一些存根代碼一起使用,但這不會涵蓋我的 ES 代碼中編寫的行。
如何對 ES 代碼進行單元測試? 我的 ESSink 使用elastic.Client
。 我如何嘲笑它?
我想嵌入一些模擬 ES 客戶端,它給我存根響應,我將能夠以這種方式測試我的ESSink.Write
方法。
根據您的問題,我假設您使用的是github.com/olivere/elastic
,並且您希望能夠使用存根 http 響應進行測試。 當我第一次看到這個問題時,我也從來沒有寫過使用 ES 客戶端的 Go 測試代碼。 所以,除了回答這個問題,我還分享了我是如何從 godocs 中找到答案的。
首先,我們可以看到elastic.NewClient
接受客戶端選項函數。 所以我檢查了庫提供了什么樣的客戶端選項功能。 原來,庫提供elastic.SetHttpClient
接受elastic.Doer
。 該Doer
是一個接口http.Client
可以實現。 從這里開始,答案就很清楚了。
所以,你必須:
func NewESSink()
更改為接受 http 客戶端或彈性客戶端。elastic.Doer
)。接收器
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(...)
}
在您的生產代碼中,您可以在設置 ES http 客戶端時使用http.Client{}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.