Java+TestNG+Excel接⼝⾃动化测试框架
思路:Excel管理测试⽤例,JSONPath做预期结果数据处理,测试结果回写Excel
import com.alibaba.fastjson.JSONObject;
import com.qa.utils.*;
stng.Assert;
stng.annotations.BeforeClass;
stng.annotations.DataProvider;
stng.annotations.Test;
public class AutoTest {
@DataProvider(name="testData")
public static Object[][] data() throws Exception{
TestData(Constant.FilePath,Constant.FileSheet);
}
@Test(dataProvider="testData",description="测试接⼝")
public void testApi(
String rowNumber,
String caseRowNumber,
String testCaseName,
String priority,
String apiName,
String url,
String type,
String parmsType,
String parms,
String assertKeyWord
) throws Exception{
Log.startTestCase(testCaseName);
JSONObject responseObject = null;
if ("post".equalsIgnoreCase(type)||"json".equalsIgnoreCase(parmsType)){
responseObject= RestClient.post(url,parms);
Log.info("Responce: "+String());
//WriteResponce.write(Constant.String(),Integer.parseInt(rowNumber.split("[.]")[0]),0);
System.out.println("response: "+responseObject);
}else {
//TODO
}
Log.info("断⾔Response是否与预期结果⼀致: "+assertKeyWord);
try {
//Assert.String().contains(assertKeyWord));
Assert.assertTrue(JSONPathUtil.String(),assertKeyWord));
} catch (AssertionError  error){
Log.info("断⾔Response是否与预期结果⼀致: "+assertKeyWord +" ---> 断⾔失败");
ExcelUtils.setCellData(Integer.parseInt(rowNumber.split("[.]")[0]), LastColumnNum(), "Fail");
Log.info("测试结果成功写⼊excel数据⽂件中的测试执⾏结果列");
Assert.fail("断⾔Response是否与预期结果⼀致: "+assertKeyWord +" 失败");
}
//System.out.println("**** "+Integer.parseInt(rowNumber.split("[.]")[0]));
//ExcelUtils.setCellData(Integer.parseInt(rowNumber.split("[.]")[0]),10,"测试执⾏成功");
Log.info("断⾔Response是否与预期结果⼀致: "+assertKeyWord +" ---> 断⾔成功");
ExcelUtils.setCellData(Integer.parseInt(rowNumber.split("[.]")[0]),LastColumnNum(),"Pass");
Log.info("测试结果成功写⼊excel数据⽂件中的测试执⾏结果列");
}
@BeforeClass
public void beforeClass() throws Exception{
ExcelUtils.setExcelFile(Constant.FilePath,Constant.FileSheet);
}
}
import com.alibaba.fastjson.JSONPath;
import com.qa.utils.Log;
import java.util.HashMap;
import java.util.Map;
public class JSONPathUtil {
public static void main(String[] args) {
String json = "{\"store\":{\"book\":[{\"title\":\"⾼效Java\",\"price\":10.2},{\"title\":\"设计模式a\",\"price\":12.21},{\"title\":\"重构\",\"isbn\":\"553\",\"price\":8},{\"title\":\"虚拟机\",\"isbn\":\"395\",\"price\":22}],\"bicycle\":{\"color\":\"red\",\"price\":19}}} //String expression1  = (String) J
//int expression2 = (int) ad(json,"$.store.book[0].price");
// 设置的检查点,多个检查点⽤;分隔
String params = "$.store.book[0].price=10.2;$.store.book[1].title=设计模式";
String[] data = params.split(";");
// 定义测试结果的标记
Boolean flag = false;
//遍历数组,获取每⼀个检查点在json中对应的数据,存在map中
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < data.length; i++) {
map.put(data[i].split("=")[0], data[i].split("=")[1]);
System.out.println("检查点"+ (i+1) +"返回的数据:" + ad(json, data[i].split("=")[0]));
System.out.println("检查点"+ (i+1) +"断⾔的数据:" + (data[i].split("=")[0]));
//判断检查点数据与返回的json数据是否⼀致
if (ad(json, data[i].split("=")[0]) instanceof String) {
if (ad(json, data[i].split("=")[0]).(data[i].split("=")[0]))) {
//System.out.println("Pass A");
flag = true;
} else {
//System.out.println("Fail A");
flag = false;
break;
}
} else { // Object转String
if ((ad(json, data[i].split("=")[0]).toString()).equals(((data[i].split("=")[0])))) {
//System.out.println("Pass B");
flag = true;
} else {
//System.out.println("Fail B");
flag = false;
break;
}
}
}
if (flag) {
System.out.println("【测试执⾏结果:通过】");
} else {
System.out.println("【测试执⾏结果:失败】");
}
}
/**
* 预期结果校验
* @param response
* @param assertKeyWord
* @return
*/
public static Boolean checkPoint(String response,String assertKeyWord){
//分隔检查点
String[] data = assertKeyWord.split(";");
// 定义测试结果的标记
Boolean flag = false;
//遍历数组,获取每⼀个检查点在json中对应的数据,存在map中
Map<String, Object> map = new HashMap<>();
for (int i = 0; i < data.length; i++) {
map.put(data[i].split("=")[0], data[i].split("=")[1]);
System.out.println("检查点"+ (i+1) +"返回的数据:" + ad(response, data[i].split("=")[0]));            System.out.println("检查点"+ (i+1) +"断⾔的数据:" + (data[i].split("=")[0]));
Log.info("检查点"+ (i+1) +"返回的数据:" + ad(response, data[i].split("=")[0]));
Log.info("检查点"+ (i+1) +"断⾔的数据:" + (data[i].split("=")[0]));
//判断检查点数据与返回的json数据是否⼀致
if (ad(response, data[i].split("=")[0]) instanceof String) {
if (ad(response, data[i].split("=")[0]).(data[i].split("=")[0]))) {
//System.out.println("Pass A");
flag = true;
} else {
//System.out.println("Fail A");
flag = false;
break;
}
} else { // Object转String
if ((ad(response, data[i].split("=")[0]).toString()).equals(((data[i].split("=")[0])))) {                    flag = true;
} else {
flag = false;
break;
}
}
}
if (flag) {
return true;
} else {
return false;
}
}
}
public class Constant {
//public static final String URL = "mail.qq";
//测试数据EXCEL路径
public static final String FilePath = "D:\\接⼝⾃动化测试.xlsx";
// EXCEL测试数据sheet名称
public static final String FileSheet = "测试⽤例";
public static final String ResponseSheet = "response";
}
import org.apache.log4j.Logger;
public class Log {
// 初始化Log4j⽇志
private static Logger Log = Logger(com.qa.utils.Name());
// 打印测试⽤例开头的⽇志
public static void startTestCase(String sTestCaseName) {
Log.info("------------------ 测试⽤例【"+ sTestCaseName + "】" + "开始执⾏ ------------------");
}
/
/打印测试⽤例结束的⽇志
public static void endTestCase(String sTestCaseName) {
Log.info("------------------ 测试⽤例【"+ sTestCaseName + "】" + "测试执⾏结束 ------------------");
}
public static void info(String message) {
Log.info(message);
}
public static void warn(String message) {
Log.warn(message);
}
public static void error(String message) {
<(message);
}
public static void fatal(String message) {
Log.fatal(message);
}
public static void debug(String message) {
Log.debug(message);
}
}
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.hods.HttpPost;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.nio.charset.Charset;
public class RestClient {
/**
* 带json参数的post请求
* @param url
* @param parms
* @return
*/
public static JSONObject post(String url, String parms) {
CloseableHttpClient httpClient = ateDefault();
HttpPost post = new HttpPost(url);
post.addHeader("content-type", "application/json;charset=utf-8");
post.setEntity(new StringEntity(parms, Charset.forName("utf-8")));
HttpResponse response = null;
String result = null;
try {
Log.info("开始发送post请求,请求的URL: " + url);
Log.info("开始发送post请求,请求的参数: " + parms);
response = ute(post);
result = Entity());
} catch (Exception e) {
e.printStackTrace();
}
if (HttpStatus.SC_OK != StatusLine().getStatusCode()) {
System.out.println("请求不正确");
}
JSONObject responseObject = JSON.parseObject(result);
//System.out.println("response: "+responseObject);
return responseObject;
}
}
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
fastjson字符串转数组import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ExcelUtils {
private static XSSFSheet sheet;
private static XSSFWorkbook workbook;
private static XSSFCell cell;
private static XSSFRow row;
/
/指定要操作的excel⽂件的路径及sheet名称
public static void setExcelFile(String path,String sheetName) throws Exception{
try {
FileInputStream  file = new FileInputStream(path);
workbook = new XSSFWorkbook(file);
sheet = Sheet(sheetName);
} catch (Exception e) {
e.printStackTrace();
}
}
//读取excel⽂件指定单元格数据(此⽅法只针对.xlsx后辍的Excel⽂件)
public static String getCellData(int rowNum,int colNum) throws Exception{
try {
//获取指定单元格对象
cell = Row(rowNum).getCell(colNum);
//获取单元格的内容
//如果为字符串类型,使⽤getStringCellValue()⽅法获取单元格内容,如果为数字类型,则⽤getNumericCellValue()获取单元格内容            String cellData = StringCellValue();
return cellData;
} catch (Exception e) {
return "";
}
}
//在EXCEL的执⾏单元格中写⼊数据(此⽅法只针对.xlsx后辍的Excel⽂件) rowNum ⾏号,colNum 列号
public static void setCellData(int rowNum,int colNum,String Result) throws Exception{
try {
//获取⾏对象
row = Row(rowNum);
//如果单元格为空,则返回null
cell = Cell(colNum);
if(cell == null){
ateCell(colNum);
cell.setCellValue(Result);
}else{
cell.setCellValue(Result);
}
FileOutputStream out = new FileOutputStream(Constant.FilePath);
//将内容写⼊excel中
workbook.write(out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/
/从EXCEL⽂件中获取测试数据
public static Object[][] getTestData(String excelFilePath,String sheetName) throws IOException {
//声明⼀个file⽂件对象
File file = new File(excelFilePath);
//创建⼀个输⼊流
FileInputStream in = new FileInputStream(file);
//声明workbook对象
Workbook workbook = null;
//判断⽂件扩展名
String fileExtensionName = excelFilePath.substring(excelFilePath.indexOf("."));
if(fileExtensionName.equals(".xlsx")){
workbook = new XSSFWorkbook(in);
}else {
workbook = new HSSFWorkbook(in);
}
//获取sheet对象
Sheet sheet = Sheet(sheetName);
//获取sheet中数据的⾏数,⾏号从0始
int rowCount = LastRowNum()-FirstRowNum();
List<Object[]> records = new ArrayList<Object[]>();
//读取数据(省略第⼀⾏表头)
for(int i=1; i<rowCount+1; i++){
/
/获取⾏对象
Row row = Row(i);
System.out.println(">>>>>>>>>>> "+ LastCellNum());
//声明⼀个数组存每⾏的测试数据,excel最后两列不需传值
String[] fields = new LastCellNum()-2];
//excel倒数第⼆列为Y,表⽰数据⾏要被测试脚本执⾏,否则不执⾏
LastCellNum()-2).getStringCellValue().equals("Y")){
//Cell(10).getStringCellValue().equals("Y")){
for(int j=0; j&LastCellNum()-2; j++){
//System.out.println("cell:"+Cell(j));
//判断单元格数据是数字还是字符
switch (Cell(j).getCellType()){
case XSSFCell.CELL_TYPE_NUMERIC:
fields[j] = String.Cell(j).getNumericCellValue());
//System.out.println(fields[j]+":"+String.Cell(j).getNumericCellValue()));
break;
case XSSFCell.CELL_TYPE_STRING:
fields[j] = Cell(j).getStringCellValue();
//System.out.println(fields[j]+":"+Cell(j).getStringCellValue());
break;
default:
fields[j] = Cell(j).getStringCellValue();
break;
}
}
/*for (int k=0;k<fields.length;k++){
System.out.println("*****:"+fields>>>>>>>>>>>[k]);
}*/
//System.out.println("********:"+Row(0).getLastCellNum());
records.add(fields);
}
}
//将list转为Object⼆维数据
Object[][] results = new Object[records.size()][];
//设置⼆维数据每⾏的值,每⾏是⼀个object对象
for(int i=0; i<records.size(); i++){
results[i]=(i);
}
return results;
}
public static int getLastColumnNum(){
//返回数据⽂件最后⼀列的列号,如果有12列则返回11
Row(0).getLastCellNum()-1;
}
}
Excel管理测试⽤例

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。