您的位置:首页 > 教育 > 锐评 > Curator Framework如何写单元测试

Curator Framework如何写单元测试

2024/10/6 16:19:50 来源:https://blog.csdn.net/MCC_MCC_MCC/article/details/139250352  浏览:    关键词:Curator Framework如何写单元测试

概述

使用curator framework框架去操作zookeeper时,我们知道因其的方法风格是那种流式的编写风格,所以我们在写单元测试的时候要把链接zookeeper的操作给mock掉,那么着实是不太好写单测。不过好在curator framework有一个专门用于测试的模块,可以让我们在单测运行之前就在本地启动一个zookeeper server实例,以便于让单测可以直接连接本地的zookeeper实例创建curator client,便于做单元测试。

实现

引入依赖

            <dependency><groupId>org.apache.curator</groupId><artifactId>curator-framework</artifactId><version>4.3.0</version></dependency><dependency><groupId>org.apache.curator</groupId><artifactId>curator-test</artifactId><version>4.3.0</version><scope>test</scope></dependency><dependency><groupId>org.apache.zookeeper</groupId><artifactId>zookeeper</artifactId><version>3.4.14</version></dependency>

启动zookeeper

    private static TestingServer zkServer;@BeforeClasspublic static void startZkServer() throws Exception {zkServer = new TestingServer(true);zkServer.start();}

创建curator framework client

    private CuratorFramework zkClient;@BeforeAllpublic CuratorFramework createCuratorClient() {zkClient = CuratorFrameworkFactory.builder()//本地启动的zookeeper实例端口,跑单测用.connectString(zkServer.getConnectString()).retryPolicy(new RetryNTimes(5, 1000)).connectionTimeoutMs(40 * 1000).sessionTimeoutMs(5 * 1000).build();zkClient.start();}

单元测试-创建临时节点

    @Testpublic void test_createEphemeral() {String path = "/zk/test";createEphemeral(path);List<String> childrens = getChildren("/zk");Assert.assertEquals(1, childrens.size());}private void createEphemeral(String path) {try {zkClient.create().withMode(CreateMode.EPHEMERAL).forPath(path);} catch (NodeExistsException e) {logger.warn("ZNode " + path + " already exists.", e);throw new IllegalStateException(e.getMessage(), e);} catch (Exception e) {throw new IllegalStateException(e.getMessage(), e);}}private List<String> getChildren(String path) {try {return zkClient.getChildren().forPath(path);} catch (NoNodeException e) {return new ArrayList<>();} catch (Exception e) {throw new IllegalStateException(e.getMessage(), e);}}

单测完毕后关闭zookeeper server

@AfterClass
public static void closeZkServer() throws IOException {zkServer.close();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com