如何在Golang中模拟Zookeeper服务器进行单元测试?

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

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)

@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.