如何针对Zookeeper测试应用程序

时间:2015-04-17 17:37:41

标签: apache apache-zookeeper apache-curator

我有一个使用Curator框架来确定领导力的应用程序。我们希望能够从Zookeeper服务器测试状态更改,有没有办法做到这一点?

从我们的角度来看,如果我们可以让服务器向连接的客户端发送连接状态(CONNECTED,RECONNECTED,SUSPENDED,LOST)将是有益的。我知道Curator提供了一个TestingServer类,但它似乎没有这个功能。

非常感谢任何解决方案或想法!

1 个答案:

答案 0 :(得分:0)

https://apache.googlesource.com/curator/+/refs/heads/CURATOR-190/curator-recipes/src/test/java/org/apache/curator/framework/client/TestBackgroundStates.java

@Test
public void testConnectionStateListener() throws Exception
{
    server.close();
    Timing timing = new Timing();
    CuratorFramework client = CuratorFrameworkFactory.newClient(server.getConnectString(), timing.session(), timing.connection(), new RetryOneTime(timing.milliseconds()));
    try
    {
        client.start();
        final BlockingQueue<ConnectionState> stateVector = Queues.newLinkedBlockingQueue(1);
        ConnectionStateListener listener = new ConnectionStateListener()
        {
            @Override
            public void stateChanged(CuratorFramework client, ConnectionState newState)
            {
                stateVector.offer(newState);
            }
        };
        Timing waitingTiming = timing.forWaiting();
        client.getConnectionStateListenable().addListener(listener);
        server = new TestingServer(server.getPort());
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.CONNECTED);
        server.stop();
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED);
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST);
        server.restart();
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.RECONNECTED);
        server.close();
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.SUSPENDED);
        Assert.assertEquals(stateVector.poll(waitingTiming.milliseconds(), TimeUnit.MILLISECONDS), ConnectionState.LOST);
    }
    finally
    {
        CloseableUtils.closeQuietly(client);
    }
}