英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论