Karate集成Cassandra:如何从Feature文件传查询与配置至Java数据库工具
改造Cassandra工具类以适配Karate框架全局复用
你现有的Java Cassandra数据库工具类依赖本地属性文件读取配置,查询语句硬编码,无法在Karate框架中灵活复用。以下是具体改造方案和代码:
原工具类代码
package Utilities; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Properties; public class DatabaseConnectionUtils { public static Properties readPropertiesFile(String fileName) throws IOException { FileInputStream fis = null; Properties prop = null; try { fis = new FileInputStream(fileName); prop = new Properties(); prop.load(fis); } catch(FileNotFoundException fnfe) { fnfe.printStackTrace(); } finally { fis.close(); } return prop; } public static void connect(String serverIP, Integer port, String keyspace, String username, String password) { Cluster cluster; Session session; Cluster.Builder b = Cluster.builder().addContactPoint(serverIP); if (port != null) { b.withPort(port).withCredentials(username,password); } cluster = b.build(); session = cluster.connect(keyspace); String cqlStatement = "select * from partner_configuration where partnerid='15918' allow filtering;"; for (Row row : session.execute(cqlStatement)) { System.out.println(row.toString()); } session.close(); } public static void main(String[] args) throws IOException { Properties prop = readPropertiesFile("C:\\NMS-Framework\\untitled\\src\\test\\resources\\DB-Credentials.properties"); String address=prop.getProperty("ServerIP"); int port= Integer.parseInt(prop.getProperty("port")); String keyspace=prop.getProperty("keyspace"); String username=prop.getProperty("username"); String password= prop.getProperty("password"); connect(address,port,keyspace,username,password); } }
改造方案与代码
关键改造说明
- 拆分连接与查询逻辑,让工具类支持传入任意CQL语句
- 移除本地属性文件依赖,所有数据库配置通过参数传入
- 用try-with-resources自动管理Cluster和Session,避免连接泄漏
- 返回
List<Map<String, Object>>格式的结果,适配Karate的断言和处理逻辑
改造后的工具类
package Utilities; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Row; import com.datastax.driver.core.Session; import com.datastax.driver.core.ColumnDefinitions; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class DatabaseConnectionUtils { // 对外暴露的核心方法:传入配置和CQL,返回结构化查询结果 public static List<Map<String, Object>> executeQuery(String serverIP, Integer port, String keyspace, String username, String password, String cqlStatement) { List<Map<String, Object>> queryResults = new ArrayList<>(); // try-with-resources自动关闭Cluster和Session,无需手动处理 try (Cluster cluster = buildCluster(serverIP, port, username, password); Session session = cluster.connect(keyspace)) { // 遍历查询结果,转成Karate友好的Map结构 for (Row row : session.execute(cqlStatement)) { Map<String, Object> rowData = new HashMap<>(); ColumnDefinitions columns = row.getColumnDefinitions(); for (ColumnDefinitions.Definition colDef : columns) { rowData.put(colDef.getName(), row.getObject(colDef.getName())); } queryResults.add(rowData); } } catch (Exception e) { // 抛出RuntimeException让Karate捕获,便于调试 throw new RuntimeException("Cassandra查询失败: " + e.getMessage(), e); } return queryResults; } // 封装Cluster构建逻辑,简化主方法代码 private static Cluster buildCluster(String serverIP, Integer port, String username, String password) { Cluster.Builder builder = Cluster.builder().addContactPoint(serverIP); if (port != null) { builder.withPort(port); } if (username != null && password != null) { builder.withCredentials(username, password); } return builder.build(); } }
Karate Feature文件调用示例
在Karate里可以直接通过Java.type调用改造后的工具类,灵活传入配置和查询语句:
Feature: Cassandra数据库查询测试 Background: # 引入工具类 * def DbUtils = Java.type('Utilities.DatabaseConnectionUtils') # 定义数据库配置(可以放在config文件里全局复用) * def dbConfig = { serverIP: '192.168.1.100', port: 9042, keyspace: 'your_keyspace', username: 'test_user', password: 'test_pass' } Scenario: 执行自定义CQL查询 # 传入要执行的查询语句 * def cqlQuery = "select * from partner_configuration where partnerid='15918' allow filtering;" # 调用工具类执行查询 * def results = DbUtils.executeQuery(dbConfig.serverIP, dbConfig.port, dbConfig.keyspace, dbConfig.username, dbConfig.password, cqlQuery) # 打印结果(调试用) * print "查询结果: ", results # 对结果做断言 * match results.size() == 1 * match results[0].partnerid == '15918'
额外说明
- 数据库配置可以放在Karate的全局配置文件(比如
karate-config.js)里,实现跨Feature复用 - 返回的
List<Map>结构完全兼容Karate的所有断言语法,不用额外转换 - 异常处理逻辑会把错误信息抛出,Karate会在测试报告里展示详细堆栈,方便定位问题
内容的提问来源于stack exchange,提问作者user3048388
相关产品推荐
相关产品推荐

