如何在Golang中为单元测试模拟一个Zookeeper服务器?

huangapple go评论83阅读模式
英文:

How to mock a Zookeeper server for unit test in golang?

问题

我正在使用库gozk将我的应用程序与生产Zookeeper服务器进行接口交互。我想测试应用程序是否创建了正确的节点,这些节点是否包含了各种情况下的正确内容,并且DataWatch和NodeWatch是否被正确设置:即应用程序根据节点和数据更新执行了应有的操作。

在单元测试期间,我能否创建和销毁一个模拟的Zookeeper服务器,并且能够人为地创建新节点并设置节点内容?是否有其他方法可以代替手动创建Zookeeper服务器并使用它?

已经存在一个解决方案适用于java

英文:

I am using the library gozk to interface my application with a production zookeeper server. I'd like to test that the application create the correct nodes, that they contain the correct content for various cases, and that the DataWatch and NodeWatch are set properly:

i.e. the application performs exactly what should based on the node and data updates.

Can I have a mock zookeeper server to be created and destroyed during unit tests only, with capability to artificially create new node and set node contents?
Is there a different way than to manually create a zookeeper server and use it?

A solution already exists for java

答案1

得分: 2

我建议将调用zookeeper的代码部分变成一个接口。

然后在测试过程中,你可以使用一个名为"mockZookeeperConn"的对象来替代,它会返回一些值,就好像它真的连接到了服务器一样(但返回的值是硬编码的)。

英文:

I would recommend making the code of yours that calls zookeeper become an interface.

Then during testing you sub in a 'mockZookeeperConn' object that just returns values as though it was really connecting to the server (but the return values are hardcoded)

答案2

得分: 0

@Ben Echols的回答非常好。

此外,你可以尝试使用"构建约束"(build constraints)。

你可以在真实的zk和模拟的zk代码上配置不同的构建标签。

例如,我们为真实的zk代码配置"product",为模拟的zk代码配置"mock"。

因此,有两种运行单元测试的方式:

  • 如果没有zk环境,可以使用go test -tags mock
  • 如果有可用的zk环境,可以使用go test -tags product
英文:

@Ben Echols 's answer is very good.

As further, you can try "build constraints".

You can configure different build tags on real-zk and mock-zk code.

For example, we configure "product" for real-zk code and "mock" for mock-zk code.

Thus there are two ways to run unittests:

  • go test -tags mock if there isn't a zk env.
  • go test -tags product if there is an available zk env.

huangapple
  • 本文由 发表于 2017年2月8日 01:53:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/42096675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定