【问题标题】:How to unit test go code that interacts with Elasticsearch如何对与 Elasticsearch 交互的 go 代码进行单元测试
【发布时间】:2020-06-22 12:28:52
【问题描述】:

我有一个应用程序,它定义了一个 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 方法。

【问题讨论】:

  • 与模拟任何东西的方式相同,您必须将elastic.Client 字段替换为定义您使用的方法的接口,然后创建一个满足用于测试的接口的模拟。

标签: unit-testing go testing mocking


【解决方案1】:

根据您的问题,我假设您使用的是github.com/olivere/elastic,并且您希望能够使用存根 http 响应进行测试。当我第一次阅读这个问题时,我也从未编写过使用 ES 客户端的 Go 测试代码。所以,除了回答这个问题,我还分享了我是如何从 godocs 中找到答案的。

首先,我们可以看到elastic.NewClient 接受客户端选项函数。所以我检查了库提供了什么样的客户端选项功能。结果库提供了接受elastic.Doerelastic.SetHttpClientDoerhttp.Client 可以实现的接口。从这里,答案变得清晰。

所以,你必须:

  1. 将您的 func NewESSink() 更改为接受 http 客户端或弹性客户端。
  2. 编写存根 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(...)
}

在您的生产代码中,您可以在设置 ES http 客户端时使用http.Client{}

【讨论】:

  • 我什至都懒得看选项,正在考虑完全放弃测试这个的想法,非常感谢@erick-wijaya
猜你喜欢
  • 2012-06-20
  • 2023-03-17
  • 2013-12-12
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多