首页 / JAVA / Java + Excel 接口自动化
Java + Excel 接口自动化
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java + Excel 接口自动化,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含24579字,纯文字阅读大概需要36分钟。
内容图文
最近项目比较悠闲,想找点事干,写了个 Excel 接口测试的 "框架" 以前用 python 写过一个,这次用 java, 应该说框架都不算,反正就是写了,能帮我解决问题就行。
当然咯,也许会问干嘛那么麻烦直接用 feed4testng, 或者 testng 就行了,没事找事干还专门写个这玩意... 呵呵,就闲的蛋疼!
文笔有限不知道怎么写,直接上代码:
欢迎各位指定,或提出好的意见,总觉得还有很多不好的地方。
结构就这破样了, E 文也不好, 随便捣鼓,开心就好。 哈哈
ExcelUtil.java 类:
1 package com.hozhu.excel; 2 3 import java.io.BufferedInputStream; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.IOException; 8 import java.util.ArrayList; 9 import java.util.HashMap; 10 import java.util.List; 11 import java.util.Map; 12 13 import org.apache.log4j.Logger; 14 import org.apache.poi.ss.usermodel.CellStyle; 15 import org.apache.poi.ss.usermodel.IndexedColors; 16 import org.apache.poi.xssf.usermodel.XSSFCell; 17 import org.apache.poi.xssf.usermodel.XSSFCellStyle; 18 import org.apache.poi.xssf.usermodel.XSSFRow; 19 import org.apache.poi.xssf.usermodel.XSSFSheet; 20 import org.apache.poi.xssf.usermodel.XSSFWorkbook; 21 22 /** 23 * 只支持读取 .xlsx 所有方法读取数据时, 未对 Excel 格式类型进行判断处理 如 Excel 中有特殊数据类型, 需在 Excel 24 * 中标注为文本类型, 程序才能正常处理 25 * 26 * @author Roger 27 * @version 1.0 28 */ 29 public class ExcelUtil { 30 private static Logger logger = Logger.getLogger(ExcelUtil.class); 31 32private String filePath = null; 33private String sheetName = null; 34 35public String getSheetName() { 36return sheetName; 37 } 38 39publicvoid setSheetName(String sheetName) { 40this.sheetName = sheetName; 41 } 42 43public String getFilePath() { 44return filePath; 45 } 46 47publicvoid setFilePath(String filePath) { 48this.filePath = filePath; 49 } 50 51/** 52 * 判断成员变量 filePath 是否为空 53 * 54 * @return 55*/ 56privateboolean isFilePathEmpty() { 57boolean flag = false; 58if ((null != filePath && (!filePath.equals("")))) { 59 flag = true; 60 } 61return flag; 62 } 63 64privateboolean isSheetNameEmpty() { 65boolean flag = false; 66if ((null != sheetName && (!sheetName.equals("")))) { 67 flag = true; 68 } 69return flag; 70 } 71 72// 使用静态内部类创建外部类对象 73privatestaticclass Excel { 74privatestatic ExcelUtil excelUtil = new ExcelUtil(); 75 } 76 77private ExcelUtil() { 78 } 79 80// 获取 ExcelUtil 实例 81publicstatic ExcelUtil getInstance() { 82return Excel.excelUtil; 83 } 84 85/** 86 * 检查传入的文件后缀是否为 xlsx 87 * 88 * @param filePacht 89 * @return 90*/ 91publicboolean checkXlsx(File file) { 92boolean flag = false; 93 94if (file.exists()) { 95 String str = file.getName(); 96if (str.substring(str.lastIndexOf(".") + 1).equals("xlsx")) 97 flag = true; 98 } else { 99 logger.info(file.getName() + ", 文件不存在..."); 100// System.out.println("文件不存在...");101 } 102103return flag; 104 } 105106/**107 * 108 * @param file 109 * @return true: 文件未被操作; false: 文件正在被操作. 110*/111publicboolean isFile(File file) { 112return file.renameTo(file); 113 } 114115public File createFile() { 116 File file = null; 117if (isFilePathEmpty()) { 118 file = new File(filePath); 119 } else { 120 logger.error("filePath 不能为: " 121 + filePath 122 + ", 请先使用 ‘ExcelUtil.getInstance().setFilePath(filePath)‘ 设置!"); 123// System.out.println("filePath 不能为: " + filePath + 124// ", 请先使用 ‘ExcelUtil.getInstance().setFilePath(filePath)‘ 设置!");125 System.exit(-1); 126 } 127return file; 128 } 129130/**131 * 创建 XSSFWorkbook 132 * 133 * @param 文件路径 134 * @return135*/136public XSSFWorkbook createExcelWorkBook() { 137 File file = createFile(); 138139 BufferedInputStream in = null; 140 XSSFWorkbook book = null; 141142if (checkXlsx(file)) { 143try { 144 in = new BufferedInputStream(new FileInputStream(file)); 145 book = new XSSFWorkbook(in); 146 } catch (IOException e) { 147 e.printStackTrace(); 148 } 149 } 150return book; 151 } 152153/**154 * 创建 XSSFSheet 155 * 156 * @param sheetName 157 * @return158*/159public XSSFSheet createExcelSheet(String sheetName) { 160 XSSFSheet sheet = null; 161if (isSheetNameEmpty()) { 162 XSSFWorkbook book = createExcelWorkBook(); 163if (book != null) { 164int sheetCount = book.getNumberOfSheets(); 165for (int i = 0; i < sheetCount; i++) { 166if (sheetName.equals(book.getSheetName(i))) { 167 sheet = book.getSheet(sheetName); 168break; 169 } 170 } 171 } 172 } else { 173 logger.error("sheetName 不能为: " 174 + sheetName 175 + ", 请先使用 ‘ExcelUtil.getInstance().setSheetName(SheetName)‘ 设置!"); 176// System.out.println("sheetName 不能为: " + sheetName + 177// ", 请先使用 ‘ExcelUtil.getInstance().setSheetName(SheetName)‘ 设置!");178 System.exit(-1); 179 } 180181return sheet; 182 } 183184/**185 * 获取指定行 186 * 187 * @param sheetName 188 * @param line 189 * 行索引, 从 0 开始 190 * @return191*/192public XSSFRow getExcelRow(int line) { 193 XSSFRow row = null; 194if (line <= getSheetMaxRow()) 195 row = createExcelSheet(sheetName).getRow(line); 196return row; 197 } 198199/**200 * 获取指定 sheet 中最大行数 201 * 202 * @param sheetName 203 * @return204*/205publicint getSheetMaxRow() { 206int maxRow = -1; 207if (createExcelSheet(sheetName) != null) 208 maxRow = createExcelSheet(sheetName).getLastRowNum(); 209return maxRow; 210 } 211212/**213 * 使用正则表达式去掉多余的.与0 214 * 215 * @param s 216 * @return217*/218private String subZeroAndDot(String s) { 219if (s.indexOf(".") > 0) { 220// 去掉多余的 0221 s = s.replaceAll("0+?$", ""); 222// 如果最后一位是.则去掉223 s = s.replaceAll("[.]$", ""); 224 } 225return s; 226 } 227228/**229 * 获取 Excel 指定行数据 230 * 231 * @param sheetName 232 * @param line 233 * @return 返回一个一维数组 234*/235public String[] readExcelRows(int line) { 236 String[] result = null; 237 XSSFRow row = getExcelRow(line); 238int maxRow = getSheetMaxRow(); 239if (row != null && maxRow > -1) { 240int columnNum = row.getLastCellNum(); 241 result = new String[columnNum]; 242for (int i = 0; i < columnNum; i++) { 243// 判断单元格是否为空, 不进行判断时, 如遇到空白单元格时, 抛出空指针异常244if (null != row.getCell(i)) 245 result[i] = subZeroAndDot(row.getCell(i).toString().trim()); 246 } 247 } 248return result; 249 } 250251/**252 * 获取指定单元格中内容 253 * 254 * @param sheetName 255 * @param line 256 * 行 257 * @param column 258 * 列 259 * @return260*/261public String readExcelCell(int line, int column) { 262 String[] value = null; 263 String result = ""; 264 value = readExcelRows(line); 265if (value != null) { 266 result = value[column]; 267 } 268return result; 269 } 270271/**272 * 从指定行开始读取 Excel 中所有数据 273 * 274 * @param sheetName 275 * sheet 名称 276 * @param line 277 * 表标题所在行 278 * @return 返回一个包含 HashMap<String, String> 的 ArrayList; 格式:[{第一行数据},{第二行数据}] 279 * {列 1 标题 = 列 1 值, 列 2 标题 = 列 2 值} 280*/281public List<Map<String, String>> readExcelAllData(int line) { 282 List<Map<String, String>> result = new ArrayList<Map<String, String>>(); 283// 读取标题行284 String[] titleRow = readExcelRows(line); 285int maxRow = getSheetMaxRow(); 286 XSSFRow row; 287if (null != titleRow && maxRow != -1) { 288// i = line + 1; 标题的下一行开始取数据289for (int i = line + 1; i <= maxRow; i++) { 290 row = getExcelRow(i); 291 Map<String, String> map = new HashMap<String, String>(); 292for (int j = 0; j < row.getLastCellNum(); j++) { 293if (null != row.getCell(j)) { 294 String value = subZeroAndDot(row.getCell(j).toString() 295 .trim()); 296 map.put(titleRow[j], value); 297 } 298 } 299 result.add(map); 300 } 301 } 302return result; 303 } 304305/**306 * 从指定数据行开始读取 Excel 所有数据 307 * 308 * @param sheetName 309 * sheet 名称 310 * @param line 311 * 数据读取开始行 312 * @return313*/314public String[][] readDataArrayAll(int line) { 315 ArrayList<Object> list = new ArrayList<Object>(); 316int maxRow = getSheetMaxRow(); 317 XSSFRow row = null; 318int columnNum = 0; 319if (maxRow != -1) { 320for (int i = line; i <= maxRow; i++) { 321 row = getExcelRow(i); 322 columnNum = row.getLastCellNum(); 323 String[] values = new String[columnNum]; 324325for (int j = 0; j < columnNum; j++) { 326if (null != row.getCell(j)) { 327 String tempStr = subZeroAndDot(row.getCell(j) 328 .toString().trim()); 329 values[j] = tempStr; 330 } 331 } 332 list.add(values); 333 } 334 } 335336 String[][] result = new String[list.size()][columnNum]; 337338for (int i = 0; i < result.length; i++) { 339 result[i] = (String[]) list.get(i); 340 } 341return result; 342 } 343344/**345 * 从指定数据行开始读取 Excel 所有数据 346 * 347 * @param sheetName 348 * sheet 名称 349 * @param line 350 * 数据读取开始行 351 * @return 返回一个包含 list 的 list; 格式 [[第一行数据],[第二行数据]] 352*/353public List<List<String>> readDataListAll(int line) { 354 List<List<String>> result = new ArrayList<List<String>>(); 355356int maxRow = getSheetMaxRow(); 357 XSSFRow row = null; 358359if (maxRow != -1) { 360for (int i = line; i <= maxRow; i++) { 361 row = getExcelRow(i); 362 List<String> list = new ArrayList<String>(); 363for (int j = 0; j < row.getLastCellNum(); j++) { 364if (null != row.getCell(j)) { 365 String value = subZeroAndDot(row.getCell(j).toString() 366 .trim()); 367 list.add(value); 368 } 369 } 370 result.add(list); 371 } 372 } 373return result; 374 } 375376/**377 * 将数据写入指定单元格 378 * 379 * @param sheetName 380 * sheet 名称 381 * @param line 382 * 需写入的行 383 * @param column 384 * 需写入的列 385 * @param content 386 * 需写入的内容 387 * @throws IOException 388*/389publicvoid writeExcelCell(int line, int column, String content) 390throws IOException { 391 XSSFWorkbook book = createExcelWorkBook(); 392 XSSFSheet sheet = book.getSheet(sheetName); 393394if (line <= sheet.getLastRowNum() && line >= 0) { 395 XSSFRow row = sheet.getRow(line); 396397if (column < row.getLastCellNum() && column >= 0) { 398if (isFile(createFile())) { 399 FileOutputStream out = new FileOutputStream(createFile()); 400 XSSFCell cell = row.getCell(column); 401if (null == cell) { 402 cell = row.createCell(column); 403 } 404 cell.setCellValue(content); 405 book.write(out); 406 out.close(); 407 } else { 408 logger.error("文件: " + filePath + ", 正被使用, 请关闭! 程序执行终止..."); 409// System.out.println("文件: " + filePath 410// + ", 正被使用, 请关闭! 程序执行终止...");411 System.exit(-1); 412 } 413 } else414 logger.error("列索引越界..."); 415// System.out.println("列索引越界...");416 } else417 logger.error("行索引越界..."); 418// System.out.println("行索引越界...");419 } 420421/**422 * 从指定行的下一行开始读取某列的所有数据 423 * @param titleLineIndex 指定行读取 424 * @param columnName 列名 425 * @return426*/427public String[] readExcelColumnData(int titleLineIndex, String columnName) { 428 String[] result = null; 429int columnIndex = getColumnIndex(titleLineIndex, columnName); 430int maxRow = getSheetMaxRow(); 431432if (columnIndex != -1 && maxRow != -1) { 433 result = new String[maxRow - titleLineIndex]; 434435for (int i = 0; i < maxRow - titleLineIndex; i++) { 436 result[i] = readExcelCell(titleLineIndex + 1 + i, columnIndex); 437 } 438 } 439return result; 440 } 441442443/**444 * 获取列的索引 445 * 446 * @param sheetName 447 * sheet 名称 448 * @param line 449 * 需要获取的行 450 * @param columnName 451 * 列名 452 * @return453*/454publicint getColumnIndex(int line, String columnName) { 455int index = -1; 456 String[] title = readExcelRows(line); 457458if (null != title) { 459for (int i = 0; i < title.length; i++) { 460if (columnName.equals(title[i])) 461 index = i; 462 } 463 } 464return index; 465 } 466467/**468 * 设置单元格背景色 469 * 470 * @param sheetName 471 * sheet 名称 472 * @param titleRow 473 * 列标题所在行号, 索引 0 开始 474 * @param columnName 475 * 需要获取列索引的列名称 476 * @param line 477 * 需要设置颜色单元格所在行 478 * @param color 479 * 需设置的颜色; 0: 红色; 1: 绿色; 2: 灰色; 3: 黄色; 4: 白色. 480 * @throws IOException 481*/482publicvoid setCellBackgroundColor(int titleRow, String columnName, 483int line, int color) throws IOException { 484 XSSFWorkbook book = createExcelWorkBook(); 485 XSSFSheet sheet = book.getSheet(sheetName); 486487int columnIndex = getColumnIndex(titleRow, columnName); 488 XSSFRow row = sheet.getRow(line); 489 XSSFCell cell = row.getCell(columnIndex); 490 XSSFCellStyle old = cell.getCellStyle(); 491 XSSFCellStyle temp = book.createCellStyle(); 492 temp.cloneStyleFrom(old); // 拷贝旧的样式493494switch (color) { 495case 0: 496// 红色497 temp.setFillForegroundColor(IndexedColors.RED.getIndex()); 498break; 499case 1: 500// 绿色501 temp.setFillForegroundColor(IndexedColors.BRIGHT_GREEN.getIndex()); 502break; 503case 2: 504// 灰色505 temp.setFillForegroundColor(IndexedColors.GREY_50_PERCENT 506 .getIndex()); 507break; 508case 3: 509// 黄色510 temp.setFillForegroundColor(IndexedColors.YELLOW.getIndex()); 511break; 512case 4: 513// 白色514 temp.setFillForegroundColor(IndexedColors.WHITE.getIndex()); 515break; 516default: 517 System.out.println("设定颜色参数 (color) 错误..."); 518break; 519 } 520521 temp.setFillPattern(CellStyle.SOLID_FOREGROUND); 522// XSSFFont font = book.createFont(); 523// font.setFontHeightInPoints((short)9); // 字体大小 524// font.setFontName("宋体"); 525// temp.setFont(font);526 cell.setCellStyle(temp); 527if (isFile(createFile())) { 528 FileOutputStream out = new FileOutputStream(createFile()); 529 book.write(out); 530 out.close(); 531 } else { 532 logger.error("文件: " + filePath + ", 正被使用, 请关闭! 程序执行终止..."); 533// System.out.println("文件: " + filePath + ", 正被使用, 请关闭! 程序执行终止...");534 System.exit(-1); 535 } 536 } 537538 }
HttpRequester.java类:
1 package com.hozhu.api; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStreamReader; 6 import java.io.PrintWriter; 7 import java.net.HttpURLConnection; 8 import java.net.URL; 9 import java.util.HashMap; 10 import java.util.Map; 11 12 public class HttpRequester { 13 /** 14 * 向指定 URL 发送POST方法的请求 15 * 16 * @param method 17 * 指定请求方法:GET, POST 等 18 * @param url 19 * 发送请求的 URL 20 * @param param 21 * 请求参数,请求参数是 name1=value1&name2=value2 的形式。 22 * @return result 返回结果 23 */ 24 public static Map<String, String> sendPost(String method, String url, 25 String param) { 26 PrintWriter out = null; 27 BufferedReader br = null; 28 String result = ""; 29int responseCode = 0; 30 Map<String, String> map = new HashMap<String, String>(); 31try { 32// 打开和URL之间的连接 33 HttpURLConnection httpConn = (HttpURLConnection) new URL(url) 34 .openConnection(); 35 36// 发送POST请求必须设置如下两行 37// 设置可输入、 可输出 38 httpConn.setDoInput(true); 39 httpConn.setDoOutput(true); 40 41 httpConn.setReadTimeout(150000); 42 httpConn.setConnectTimeout(15000); 43 44// 连接后不自动跳转 45 httpConn.setInstanceFollowRedirects(false); 46 47// 设置通用的请求属性 48 httpConn.setRequestProperty("Accept-Charset", "utf-8"); 49 httpConn.setRequestProperty("User-Agent", "systempatch"); 50 httpConn.setRequestProperty("Accpet-Encoding", "gzip"); 51 52// 设置提交方式 53 httpConn.setRequestMethod(method); 54 55// httpConn.connect(); 56 57// 获取HttpURLConnection对象对应的输出流 58 out = new PrintWriter(httpConn.getOutputStream()); 59 60// 发送请求参数 61 out.print(param); 62 out.flush(); 63 responseCode = httpConn.getResponseCode(); 64 map.put("code", String.valueOf(responseCode)); 65// 打印 http 状态码 66// System.out.println("responseCode: " + responseCode); 67 68if (HttpURLConnection.HTTP_OK == responseCode) { 69// 定义BufferedReader输入流来读取URL的响应 70 br = new BufferedReader(new InputStreamReader( 71 httpConn.getInputStream(), "utf-8")); 72 String strLine; 73 StringBuffer responseBuf = new StringBuffer(); 74 75while ((strLine = br.readLine()) != null) { 76 responseBuf.append(strLine); 77 } 78 79 result = responseBuf.toString(); 80 map.put("result", result); 81 } 82 83 } catch (Exception e) { 84 System.out.println("发送 POST 请求出现异常!" + e); 85 e.printStackTrace(); 86 } 87// 使用finally块来关闭输出流、输入流 88finally { 89try { 90if (out != null) { 91 out.close(); 92 } 93if (br != null) { 94 br.close(); 95 } 96 } catch (IOException ex) { 97 ex.printStackTrace(); 98 } 99 } 100return map; 101 } 102 }
MobileApiTools.java 类
1 package com.hozhu.api; 2 3 import java.io.IOException; 4 import java.text.SimpleDateFormat; 5 import java.util.Date; 6 7 import com.hozhu.excel.ExcelUtil; 8 9 public class MobileApiTools { 10 private MobileApiTools() { 11 } 12 13 /** 14 * 获取当前系统时间 15 * 16 * @return 17 */ 18 public static String getDate() { 19 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 20return df.format(new Date()); 21 } 22 23/** 24 * 期望结果与实际结果比较 25 * 26 * @param expectedResult 27 * @param actualResult 28 * @return 29*/ 30publicstatic String assertResult(String expectedResult, String actualResult) { 31 String result; 32if (expectedResult.equals(actualResult)) 33 result = "OK"; 34else 35 result = "NG"; 36return result; 37 38 } 39 40/** 41 * 初始化 Excel 中指定列数据 42 * 43 * @param filePath 44 * 文件路径 45 * @param sheetName 46 * sheet 名称 47 * @param titleLineIndex 48 * 表标题所在行索引 49 * @param columnName 50 * 列名称 51 * @param content 52 * 需写入的内容 53 * @param color 54 * 需设置的单元格颜色 55 * @throws IOException 56*/ 57publicstaticvoid initializeData(int titleLineIndex, String columnName, 58 String content, int color) throws IOException { 59int maxRow = ExcelUtil.getInstance().getSheetMaxRow(); 60int columnIndex = ExcelUtil.getInstance().getColumnIndex( 61 titleLineIndex, columnName); 62if (maxRow != -1 && columnIndex != -1) { 63for (int i = titleLineIndex + 1; i <= maxRow; i++) { 64// 初始化单元格内容 65 ExcelUtil.getInstance().writeExcelCell(i, columnIndex, content); 66// 设置单元格颜色 67 ExcelUtil.getInstance().setCellBackgroundColor(titleLineIndex, 68 columnName, i, color); 69 } 70 } 71 } 72 73/** 74 * 将执行结果写入 Excel 中 75 * 76 * @param filePath 77 * 文件路径 78 * @param sheetName 79 * sheet 名称 80 * @param titleLineIndex 81 * 标题所在索引行 82 * @param writeStartRow 83 * 写入起始行 84 * @param columnName 85 * 列名称 86 * @param content 87 * 写入内容 88*/ 89publicstaticvoid writeResult(int titleLineIndex, int writeStartRow, 90 String columnName, String content) { 91 92int columnIndex = ExcelUtil.getInstance().getColumnIndex( 93 titleLineIndex, columnName); 94if (columnIndex != -1) { 95try { 96 ExcelUtil.getInstance().writeExcelCell(writeStartRow, 97 columnIndex, content); 98 } catch (IOException e) { 99 e.printStackTrace(); 100 } 101 } 102 } 103104/**105 * 表标题行是否包含指定参数 106 * @param argLineIndex 参数名称所在单元格行索引 107 * @param argColumnIndex 参数名称所在单元格列索引 108 * @param titleLineIndex 表标题所在行索引 109 * @return110*/111publicstaticboolean isArgEquals(int argLineIndex, int argColumnIndex, 112int titleLineIndex) { 113 String[] argArray = null; 114boolean flag = false; 115116// 获取所在单元格的参数列表117 String args = ExcelUtil.getInstance().readExcelCell(argLineIndex, argColumnIndex); 118if (!args.equals("")) { 119 argArray = args.split("\\|"); 120 } else { 121 System.out.println("文件: " + ExcelUtil.getInstance().getFilePath() 122 + ", sheetName: " + ExcelUtil.getInstance().getSheetName() 123 + ", 获取参数失败..."); 124 } 125126if (argArray != null) { 127for (int i = 0; i < argArray.length; i++) { 128int tempIndex = ExcelUtil.getInstance().getColumnIndex( 129 titleLineIndex, argArray[i]); 130if (tempIndex >= 0) 131 flag = true; 132else133 System.out.println("参数: " + argArray[i] 134 + ", 不存在表标题行中, 请检查..."); 135 } 136 } 137return flag; 138 } 139140publicvoid info() { 141142 } 143 }
LoginAPI.java 类
1 package com.hozhu.cases; 2 3 import java.io.IOException; 4 import java.util.List; 5 import java.util.Map; 6 7 import org.apache.log4j.Logger; 8 import org.json.JSONException; 9 import org.json.JSONObject; 10 11 import com.hozhu.api.HttpRequester; 12 import com.hozhu.api.MobileApiTools; 13 import com.hozhu.excel.ExcelUtil; 14 15 public class LoginAPI { 16 private static Logger logger = Logger.getLogger(LoginAPI.class); 17 18privatefinal String FILE_PATH = "mobileApiCase.xlsx"; 19privatefinal String SHEET_NAME = "Login"; 20privatefinalint TITLE_LINE_INDEX = 4; 21 22privatefinal String RESULT_CODE = "ResultCode"; 23privatefinal String TEST_RESULT = "TestResult"; 24privatefinal String RUNNING_TIME = "RunningTime"; 25privatefinal String ACTUAL_RESULT = "ActualResult"; 26privatefinal String RUN = "Run"; 27 28// 需要的参数常量 29privatefinal String MAIL = "mail"; 30privatefinal String MOBILE = "mobile"; 31privatefinal String PASS_WORD = "password"; 32 33public LoginAPI() { 34try { 35 logger.info(LoginAPI.class); 36 37 ExcelUtil.getInstance().setFilePath(FILE_PATH); 38 ExcelUtil.getInstance().setSheetName(SHEET_NAME); 39 40 logger.info("初始化: " + ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName()); 41 42 MobileApiTools.initializeData(TITLE_LINE_INDEX, RUN, "N", 4); 43 MobileApiTools.initializeData(TITLE_LINE_INDEX, ACTUAL_RESULT, "", 44 4); 45 MobileApiTools.initializeData(TITLE_LINE_INDEX, RESULT_CODE, "", 4); 46 MobileApiTools.initializeData(TITLE_LINE_INDEX, TEST_RESULT, "NT", 47 2); 48 MobileApiTools 49 .initializeData(TITLE_LINE_INDEX, RUNNING_TIME, "", 4); 50 51 logger.info(ExcelUtil.getInstance().getFilePath() + ", " + ExcelUtil.getInstance().getSheetName() + "初始化完成"); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 } 56 57publicvoid login() throws JSONException, IOException { 58 String url = ""; 59 String act = ""; 60 String method = ""; 61 List<Map<String, String>> data = null; 62boolean flag = false; 63 64 url = ExcelUtil.getInstance().readExcelCell(0, 1); 65 act = ExcelUtil.getInstance().readExcelCell(1, 1); 66 method = ExcelUtil.getInstance().readExcelCell(2, 1); 67 flag = MobileApiTools.isArgEquals(3, 1, TITLE_LINE_INDEX); 68 69if (url.equals("") || act.equals("") || method.equals("") || !flag) { 70 logger.error("请检查 Excel 中 Interface、Act、Method、ArgName 是否设置正确..."); 71//System.out 72// .println("请检查 Excel 中 Interface、Act、Method、ArgName 是否设置正确..."); 73 System.exit(-1); 74 } 75 76 data = ExcelUtil.getInstance().readExcelAllData(4); 77 78if (data != null) { 79for (int i = 0; i < data.size(); i++) { 80 Map<String, String> map = data.get(i); 81 String mail = map.get(MAIL); 82 String mobile = map.get(MOBILE); 83 String password = map.get(PASS_WORD); 84 String state = map.get("State"); 85 String expectedResult = map.get("ExpectedResult"); 86 String loginName; 87 88// 如果 state == 0 则用 邮箱登录, 否则使用手机号码登录 89if (Integer.parseInt(state) == 0) 90 loginName = mail; 91else 92 loginName = mobile; 93 94 String param = "Act=" + act + "&" + "LoginName=" + loginName 95 + "&" + "Pwd=" + password; 96 97 Map<String, String> result = HttpRequester.sendPost(method, 98 url, param); 99 String code = result.get("code"); 100 String rsTmp = result.get("result"); 101102// 将字符串转换为 JSON103 JSONObject object = new JSONObject(rsTmp); 104 String actualResult = object.getString("msg"); 105106 String testResult = MobileApiTools.assertResult(expectedResult, 107 actualResult); 108109// 写入 Run 列, 执行纪录110 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX 111 + 1 + i, RUN, "Y"); 112113// 写入 http code114 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX 115 + 1 + i, RESULT_CODE, code); 116117// 设置单元格颜色118if (Integer.parseInt(code) == 200) 119 ExcelUtil.getInstance().setCellBackgroundColor( 120 TITLE_LINE_INDEX, RESULT_CODE, 121 TITLE_LINE_INDEX + 1 + i, 1); 122else123 ExcelUtil.getInstance().setCellBackgroundColor( 124 TITLE_LINE_INDEX, RESULT_CODE, 125 TITLE_LINE_INDEX + 1 + i, 1); 126127// 写入实际结果128 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX 129 + 1 + i, ACTUAL_RESULT, actualResult); 130131// 写入测试通过与否132 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX 133 + 1 + i, TEST_RESULT, testResult); 134135if (testResult.equals("OK")) 136 ExcelUtil.getInstance().setCellBackgroundColor( 137 TITLE_LINE_INDEX, TEST_RESULT, 138 TITLE_LINE_INDEX + 1 + i, 1); 139else140 ExcelUtil.getInstance().setCellBackgroundColor( 141 TITLE_LINE_INDEX, TEST_RESULT, 142 TITLE_LINE_INDEX + 1 + i, 0); 143144// 写入执行时间145 MobileApiTools.writeResult(TITLE_LINE_INDEX, TITLE_LINE_INDEX 146 + 1 + i, RUNNING_TIME, MobileApiTools.getDate()); 147148 logger.info("CaseID: " + map.get("CaseID") + ", CaseName: " + map.get("CaseName") + ", ExpectedResult: " + 149 map.get("ExpectedResult") + ", ActualResult: " + actualResult + ", ResultCode: " + code + 150 ", TestResult: " + testResult); 151 } 152 } 153154 } 155156publicstaticvoid main(String[] args) throws JSONException, IOException { 157 LoginAPI loginAPI = new LoginAPI(); 158 loginAPI.login(); 159160 } 161162 }
RunCase.java : 所有的 case 都放这里运行
1 package com.hozhu.cases; 2 3 import java.io.IOException; 4 5 import org.json.JSONException; 6 import org.testng.Assert; 7 import org.testng.annotations.Test; 8 9 import com.hozhu.excel.ExcelUtil; 10 11 public class RunCase { 12 @Test 13 public void testLogin() throws JSONException, IOException { 14 LoginAPI login = new LoginAPI(); 15 login.login(); 16 String [] result = ExcelUtil.getInstance().readExcelColumnData(4, "TestResult"); 17for (int i = 0; i < result.length; i++) { 18 Assert.assertEquals(result[i], "OK"); 19 } 20 } 21 }
好了, 上传完毕,等等, 还有那 excel 也上截图吧,呵呵
原文:http://www.cnblogs.com/Roger1227/p/3887185.html
内容总结
以上是互联网集市为您收集整理的Java + Excel 接口自动化全部内容,希望文章能够帮你解决Java + Excel 接口自动化所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。