1.实现目标
先将常用变量占位符替换为实际值,然后解析并执行初始化sql,保证用例中的数据可用,这样不用每次执行测试前修改测试数据。
2.添加pom依赖
连接操作数据库(pom.xml文件中添加)
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
解析初始化sql(json数组)(pom.xml文件中添加)
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.75</version>
</dependency>
3.添加配置文件
数据库连接配置jdbc.properties(在resources中新建jdbc.properties)
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/testjava?useUnicode=true&characterEncoding=utf-8&useSSL=true
jdbc.username=root
jdbc.password=123456
4.添加实体类
Sql
package com.syq.autotest.entity;
/**
* @description
* @author: Admin
* @create: 2024/2/28 15:23
*/
public class Sql {
private String sqlNo;
private String sql;
public String getSqlNo() {
return sqlNo;
}
public void setSqlNo(String sqlNo) {
this.sqlNo = sqlNo;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
@Override
public String toString() {
return "Sql{" +
"sqlNo='" + sqlNo + '\'' +
", sql='" + sql + '\'' +
'}';
}
}
5.添加工具类
添加JDBCUtil.java
package com.syq.autotest.utils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.HashMap;
import java.util.Properties;
/**
* @description
* @author: Admin
* @create: 2024/2/28 15:26
*/
public class JDBCUtil {
public static Logger logger = Logger.getLogger(JDBCUtil.class);
public static Properties properties = new Properties();
static {
// 解析jdbc.properties获取数据库配置信息
try {
InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
properties.load(in);
} catch (IOException e) {
logger.info("解析发生异常。");
e.printStackTrace();
}
}
public static void query(String sql){
HashMap<String, Object> stringObjectHashMap = null;
try {
// 1、调用方法,获取连接
Connection connection = getConnection();
// 2、获取PreparedStatement
Statement statement = connection.createStatement();
// 3、调用查询方法,执行查询,返回结果集(ResultSet)
ResultSet resultSet = statement.executeQuery(sql);
// 获取查询相关的信息
ResultSetMetaData metaData = resultSet.getMetaData();
// 获取sql中有多少个查询字段
int columnCount = metaData.getColumnCount();
// System.out.println("查询字段数为:" + columnCount);
stringObjectHashMap = new HashMap<String, Object>();
// 从结果集获取查询数据:循环取出每个查询字段
while (resultSet.next()){
for (int i = 1; i <= columnCount; i++) {
String columnLabel = metaData.getColumnLabel(i);
String columnValue = resultSet.getObject(columnLabel).toString();
stringObjectHashMap.put(columnLabel, columnValue);
}
}
logger.info("查询结果:" + stringObjectHashMap);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void nonQuery(String sql){
try {
// 1、调用方法,获取连接
Connection connection = getConnection();
// 2、获取statement
Statement statement = connection.createStatement();
// 3、调用查询方法,执行查询,返回结果集(ResultSet)
int n = statement.executeUpdate(sql);
if (n>0){
logger.info("操作成功数据条数:【" + n + "】");
} else {
logger.info("操作成功数据条数:【0】");
}
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取数据库连接
public static Connection getConnection() throws SQLException {
String url = properties.getProperty("jdbc.url");
String username = properties.getProperty("jdbc.username");
String password = properties.getProperty("jdbc.password");
Connection connection = DriverManager.getConnection(url, username, password);
return connection;
}
}
添加InitSqlUtil.java
package com.syq.autotest.utils;
import com.alibaba.fastjson.JSONObject;
import com.syq.autotest.entity.Sql;
import org.apache.log4j.Logger;
import java.util.List;
/**
* @description
* @author: Admin
* @create: 2024/2/28 15:39
*/
public class InitSqlUtil {
public static Logger logger = Logger.getLogger(InitSqlUtil.class);
public static void doInitSql(String initSql) {
// 初始化sql解析为对象
List<Sql> sqls = JSONObject.parseArray(initSql, Sql.class);
// 遍历获取sql,并执行
for (Sql sql_ : sqls) {
String sqlNo = sql_.getSqlNo();
String sql = sql_.getSql().trim();
// logger.info("获取到的sql:sqlNo="+sqlNo+", sql=" + sql);
String prefix = sql.split(" ")[0].trim().toLowerCase();
if (prefix.startsWith("select")){
logger.info("=====执行select语句:" + sql_);
// 执行查询sql,获取执行结果
JDBCUtil.query(sql);
} else if (prefix.startsWith("delete")){
logger.info("=====执行delete语句:" + sql_);
JDBCUtil.nonQuery(sql);
} else if (prefix.startsWith("update")){
logger.info("=====执行update语句:" + sql_);
JDBCUtil.nonQuery(sql);
} else if (prefix.startsWith("insert")){
logger.info("=====执行insert语句:" + sql_);
JDBCUtil.nonQuery(sql);
} else {
logger.info("=====sql语句【"+ sql_ +"】不符合规范");
}
}
}
}
6.测试方法中执行初始化sql
在BaseCase.java中添加
// 执行初始化sql
if (initSql!=null && initSql.trim().length()>0){
// 替换sql中的参数
initSql = VariableUtil.variableSubstitution(initSql);
// 调用方法
InitSqlUtil.doInitSql(initSql);
}
7.结果
运行testng.xml文件,可以看到操作数据库成功
如需要全部代码,可在资源中自行下载,如有疑问,可在评论区评论!!!