如何模拟Go的ElasticSearchSDK?

jljoyd4f  于 2023-10-14  发布在  Go
关注(0)|答案(1)|浏览(113)

我在go中开发了一个API,它使用SDK v8与ElasticSearch进行通信。但是我在模拟单元测试的弹性方法时遇到了困难
我有以下功能:

  1. func DocumentExists(id string) (bool, error) {
  2. exists, err := elastic.Client.Exists("my_index", "doc_id")
  3. if err != nil {
  4. return false, err
  5. }
  6. if exists.StatusCode != 200 {
  7. return false, nil
  8. }
  9. return true, nil
  10. }

此函数仅检查弹性文件中是否存在文档。elastic.Client是全局提供的,可在应用程序中的任何位置使用,并且具有以下类型:

  1. import elastic "github.com/elastic/go-elasticsearch/v8"
  2. var (
  3. Client *elastic.Client
  4. )

你可以试着用不同的方式来嘲笑,用嘲笑来证明。但没有成功。
我怎么能这么做?我应该改变我获得客户的方式吗?利用合同?
在我看来,在这种情况下,使用合同是没有必要的。

o3imoua4

o3imoua41#

Elasticsearch Go客户端的GitHub存储库中的官方example演示了如何为Elasticsearch客户端创建模拟。此过程主要需要使用替代HTTP传输的配置调用NewClient

  1. type MockTransport struct {
  2. Response *http.Response
  3. RoundTripFn func(req *http.Request) (*http.Response, error)
  4. }
  5. func (t *MockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
  6. return t.RoundTripFn(req)
  7. }
  8. func TestStore(t *testing.T) {
  9. mockTransport := MockTransport{
  10. Response: &http.Response{
  11. StatusCode: http.StatusOK,
  12. Body: io.NopCloser(strings.NewReader(`{}`)),
  13. Header: http.Header{"X-Elastic-Product": []string{"Elasticsearch"}},
  14. },
  15. }
  16. mockTransport.RoundTripFn = func(req *http.Request) (*http.Response, error) { return mockTransport.Response, nil }
  17. client, err := elasticsearch.NewClient(elasticsearch.Config{
  18. Transport: &mockTransport,
  19. })
  20. if err != nil {
  21. t.Fatalf("Error creating Elasticsearch client: %s", err)
  22. }
  23. // Now you can use the client for testing.
  24. }
展开查看全部

相关问题