如何模拟Kafka AdminClient返回某个主题?我想在单元测试中测试这个方法,但在模拟AdminClient时遇到了问题,它总是试图连接到真正的Kafka集群……我不能使用PowerMockito,因为Junit5,只有正常的Mockito库。
这是我的方法,谢谢你的帮助,但我是Mockito的初学者
public List<String> getTopicByAddresses(String brokerAddresses) throws TopicsNameNotFound {
List<String> result = new ArrayList<>();
Properties props = new Properties();
props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG, brokerAddresses);
try (AdminClient adminClient = AdminClient.create(props)) {
ListTopicsOptions listTopicsOptions = new ListTopicsOptions();
listTopicsOptions.timeoutMs(5000);
result = adminClient.listTopics(listTopicsOptions).names().get()
.stream().filter(StringUtils::hasLength).toList();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
} catch (Exception e) {
log.error(e.getMessage());
throw new TopicsNameNotFound("Topics name not found for connection name: " + brokerAddresses);
}
if (result.isEmpty()) {
throw new TopicsNameNotFound("Topics name not found for connection name: " + brokerAddresses);
}
return result;
}
发布于 2021-09-27 18:42:58
如注释中所述,将参数更改为使用预先配置/模拟的客户机,而不是引导服务器。
如果您想单独测试,也可以将客户端创建提取到它自己的方法中。
https://stackoverflow.com/questions/69347426
复制相似问题