接口测试 java+httpclient+testng+excel

最近研究了下java实现接口自动化,借助testng+excel实现数据驱动,记录下

 

代码记录下:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ygsoft.test</groupId>
    <artifactId>api</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>api</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.10</version>
        </dependency>

        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
            <scope>test</scope>
        </dependency>


        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.52</version>
        </dependency>
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>


        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
    </dependencies>

</project>
View Code

Paras.properties

base_url=http://10.121.55.41:8080
#Realinsight
#login_url=http://10.121.55.41:8080/api/v1/login/default
#login_request={"username":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5ea2d238b299d6ae6cfed3dbb2e7c67de081cc036d4d67a21164ebc49b6921e0acf97da44dadea9e6","password":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5a27864da748838b4d83033116215a667e802d78ce0e0097af337e89322c1ad81f5efee7a471f6ad701","code":""}
#ETL
login_url=http://10.121.55.41/api/v1/login/default
login_request={"username":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea2d71d47cb86fefccdbfed490c51512e8f32b503399d6a41b16afec106686ac52c8308b8e29474f","password":"04ba024b471d006ca514a00fbaa70c3b74cac10d79a1d0c20ffedee6d8a32778fa5c40bfc0c8e14cdb12cca64af62e2396b15d4f1e466f5319e456304fa4d652f5a27864da748838b4d83033116215a667e802d78ce0e0097af337e89322c1ad81f5efee7a471f6ad701","code":""}
login_admin={"username":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea2160c9c119431541e1673498b9740918d43042c3ba161a304ba2d079d300f5afc181ee","password":"04281739551a4a21b497fccc38a59d15a4923427f176aa34545dfae05dad2bb89033783740f7a37a1019e225312c3ea20772cbe08e43ff47db2b6e191714724aea7d338e3cf37df9abc1cb807b6f672ebfcf827c2697a91a674ac62d546b42e07ae9fe591bfb16df7667","code":""}

logout_url=http://10.121.55.41:8080/api/v1/logout

RealinsightAPI=Realinsight
etlAPI=ETL
View Code

ExcelUtil.Java

package com.ygsoft.test.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * 只支持读取 .xlsx 所有方法读取数据时
 * 
 * @version 1.0
 */
public class ExcelUtil{
    static FormulaEvaluator formulaEvaluator = null;
    static XSSFWorkbook wb;

    public static List<Map<String, String>> getTestData(String fileName, String sheetName) throws Exception {
        File file = new File(fileName);
        FileInputStream inputStream = new FileInputStream(file);
        wb = new XSSFWorkbook(inputStream);
        formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
        XSSFSheet s = wb.getSheet(sheetName);
        Map<String, String> map = null;
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        // 获取第一行作为key
        XSSFRow title = s.getRow(0);
        List<String> keys = new ArrayList<String>();
        for (int i = 0; i < title.getLastCellNum(); i++) {
            Cell cell = title.getCell(i);
            keys.add(getValue(cell));
        }

        for (int row = 1; row <= s.getLastRowNum(); row++) {
            map = new HashMap<String, String>();
            XSSFRow r = s.getRow(row);
            if (r == null) {
                continue;
            }
            // 遍历单元格 cell
            for (int cell = 0; cell <= r.getLastCellNum(); cell++) {
                XSSFCell c = r.getCell(cell); 
                if (c == null) {
                    continue;
                }
                map.put(keys.get(cell), getValue(c));
            }
            list.add(map);
        }
        if (inputStream != null) {
            inputStream.close();
        }
        if (wb != null) {
            wb.close();
        }
        return list;
    }

    public static String getValue(Cell cell) {
        if (cell.getCellType() == CellType.BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == CellType.NUMERIC) {
            NumberFormat numberFormat = NumberFormat.getInstance();
            numberFormat.setGroupingUsed(false);
            return numberFormat.format(cell.getNumericCellValue());
        } else if (cell.getCellType() == CellType.FORMULA) {
             wb.getCreationHelper().createFormulaEvaluator().evaluateFormulaCell(cell);
             String strCell;
             try {
                    strCell = String.valueOf(cell.getNumericCellValue());
                } catch (IllegalStateException e) {
                    strCell = cell.getStringCellValue();
                }
            return strCell;
        } else {
            return cell.getStringCellValue();
        }
    }
    
    

    public static void writeData(String fileName, String sheetName, int row, int column, String content, String color)
            throws Exception {
        File file = new File(fileName);
        FileInputStream inputStream = new FileInputStream(file);
        XSSFWorkbook wb = new XSSFWorkbook(inputStream);
        XSSFSheet s = wb.getSheet(sheetName);
        // 如果单元格是空就创建新单元格在修改
        if (s.getRow(row) == null) {
            s.createRow(row);
        }
        if (s.getRow(row).getCell(column) == null) {
            s.getRow(row).createCell(column);
        }
        // 填充內容
        Cell cell = s.getRow(row).getCell(column);
        cell.setCellValue(content);
        CellStyle cellStyle = wb.createCellStyle();
        // 填充单元格
        if (color == null) {
        } else if (color.contains("RED")) {
            cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else if (color.contains("GREEN")) {
            cellStyle.setFillForegroundColor(IndexedColors.GREEN.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        } else if (color.contains("YELLOW")) {
            cellStyle.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
            cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        }
        
        cell.setCellStyle(cellStyle);

        FileOutputStream outputStream = new FileOutputStream(fileName);
        wb.setForceFormulaRecalculation(true);
        XSSFFormulaEvaluator.evaluateAllFormulaCells(wb);
        wb.write(outputStream);
        outputStream.flush();
        outputStream.close();

        if (inputStream != null) {
            inputStream.close();
        }

        if (outputStream != null) {
            outputStream.close();
        }
        if (wb != null) {
            wb.close();
        }
    }

    
    public static int getRowNum(String fileName, String sheetName) throws Exception {
        File file = new File(fileName);
        FileInputStream inputStream = new FileInputStream(file);
        wb = new XSSFWorkbook(inputStream);
        formulaEvaluator = new XSSFFormulaEvaluator((XSSFWorkbook) wb);
        XSSFSheet s = wb.getSheet(sheetName);
        int rowNum=s.getLastRowNum();
        if (inputStream != null) {
            inputStream.close();
        }
        if (wb != null) {
            wb.close();
        }
        return rowNum;
    }
    
    public static int getColumnNum(String fileName, String sheetName,String columnString) throws Exception{
        int column = 0;
        FileInputStream inputStream = new FileInputStream(new File(fileName));
        wb = new XSSFWorkbook(inputStream);
        XSSFSheet s = wb.getSheet(sheetName);
        // 获取第一行
        XSSFRow title = s.getRow(0);
        for (int i = 0; i < title.getLastCellNum(); i++) {
            Cell cell = title.getCell(i);
            if (getValue(cell).contains(columnString)) {
                column=i;
            }
        }
        if (inputStream != null) {
            inputStream.close();
        }
        if (wb != null) {
            wb.close();
        }
        return column;
        
    }

}
View Code

HttpClientUtil.Java

package com.ygsoft.test.api;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.collections.map.StaticBucketMap;
import org.apache.http.*;
import org.apache.http.client.*;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.*;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.poi.ss.formula.functions.Column;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.STTabTlcImpl;
import org.testng.log4testng.Logger;

import com.alibaba.fastjson.JSONObject;

public class HttpClientUtil extends ParasUtil {

    final static Logger Log = Logger.getLogger(HttpClientUtil.class);

    public static int statusCode;
    public static String reponseContent;
    public static String Authorization;
    public static String token;

    public static HashMap<String, String> headers = new HashMap<String, String>();

    /**
     * 不带请求头的get方法封装
     * 
     * @param url
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String get(String url) throws ClientProtocolException, IOException {

        // 创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        // 执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        Log.info("开始发送get请求...");
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);
        reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        Log.info("返回内容:" + reponseContent);
        return reponseContent;
    }

    /**
     * 带请求头信息的get方法
     * 
     * @param url
     * @param headermap,键值对形式
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */
    public String get(String url, HashMap<String, String> headermap)
            throws ClientProtocolException, IOException {

        // 创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建一个HttpGet的请求对象
        HttpGet httpget = new HttpGet(url);
        // 加载请求头到httpget对象
        for (Map.Entry<String, String> entry : headermap.entrySet()) {
            httpget.addHeader(entry.getKey(), entry.getValue());
        }
        // 执行请求,相当于postman上点击发送按钮,然后赋值给HttpResponse对象接收
        CloseableHttpResponse httpResponse = httpclient.execute(httpget);
        reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        Log.info("返回内容:" + reponseContent);
        return reponseContent;
    }

    /**
     * 封装post方法
     * 
     * @param url
     * @param entityString,其实就是设置请求json参数
     * @param headermap,带请求头
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String post(String url, String entityString, HashMap<String, String> headermap)
            throws ClientProtocolException, IOException {
        // 创建一个可关闭的HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 创建一个HttpPost的请求对象
        HttpPost httppost = new HttpPost(url);
        // 设置payload
        if (entityString != null) {
            httppost.setEntity(new StringEntity(entityString));
        }

        // 加载请求头到httppost对象
        for (Map.Entry<String, String> entry : headermap.entrySet()) {
            httppost.addHeader(entry.getKey(), entry.getValue());
        }
        // 发送post请求
        CloseableHttpResponse httpResponse = httpclient.execute(httppost);
        statusCode = httpResponse.getStatusLine().getStatusCode();
        Log.info("返回状态码:" + statusCode);

        reponseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
        Log.info("返回内容:" + reponseContent);
        return reponseContent;
    }

    /**
     * 封装 put请求方法,参数和post方法一样
     * 
     * @param url
     * @param entityString,这个主要是设置payload,一般来说就是json串
     * @param headerMap,带请求的头信息,格式是键值对,所以这里使用hashmap
     * @return 返回响应对象
     * @throws ClientProtocolException
     * @throws IOException
     */
    public CloseableHttpResponse put(String url, String entityString, HashMap<String, String> headerMap)
            throws ClientProtocolException, IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPut httpput = new HttpPut(url);
        httpput.setEntity(new StringEntity(entityString));

        for (Map.Entry<String, String> entry : headerMap.entrySet()) {
            httpput.addHeader(entry.getKey(), entry.getValue());
        }
        // 发送put请求
        CloseableHttpResponse httpResponse = httpclient.execute(httpput);
        return httpResponse;
    }

    /**
     * 封装 delete请求方法,参数和get方法一样
     * 
     * @param url,
     *            接口url完整地址
     * @return,返回一个response对象,方便进行得到状态码和json解析动作
     * @throws ClientProtocolException
     * @throws IOException
     */
    public CloseableHttpResponse delete(String url) throws ClientProtocolException, IOException {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpDelete httpdel = new HttpDelete(url);

        // 发送delete请求
        CloseableHttpResponse httpResponse = httpclient.execute(httpdel);
        return httpResponse;
    }

    public static String UploadFile(String url, File file, HashMap<String, String> headermap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 每个post参数之间的分隔。随意设定,只要不会和其他的字符串重复即可。
        String boundary = "----WebKitFormBoundarya4boZUDstbGAOHbb";
        try {
            String fileName = file.getName();
            HttpPost httpPost = new HttpPost(url);
            // 加载请求头到httppost对象
            for (Map.Entry<String, String> entry : headermap.entrySet()) {
                httpPost.addHeader(entry.getKey(), entry.getValue());
            }
            httpPost.addHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName);
            builder.setCharset(Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            builder.setBoundary(boundary);
            builder.addPart("multipartFile", new FileBody(file));
            builder.addTextBody("filename", fileName, ContentType.create("text/plain", Consts.UTF_8));
            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);
            reponseContent = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("reponseContent:" + reponseContent);
        return reponseContent;
    }

    public static void login() {
        headers.put("Content-Type", "application/json;charset=UTF-8");
        try {
            String response = post(login_url, login_request, headers);
            JSONObject jsonObject = JSONObject.parseObject(response);
            token = jsonObject.getString("access_token");
            Authorization = "bearer " + jsonObject.getString("access_token");

            System.out.println("登陆成功
Authorization:" + Authorization);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void login_admin() {
        headers.put("Content-Type", "application/json;charset=UTF-8");
        try {
            String response = post(login_url, login_admin, headers);
            JSONObject jsonObject = JSONObject.parseObject(response);
            token = jsonObject.getString("access_token");
            Authorization = "bearer " + jsonObject.getString("access_token");

            System.out.println("登陆成功
Authorization:" + Authorization);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void logout() {
        headers.put("Content-Type", "application/x-www-form-urlencoded");
        headers.put("Authorization", Authorization);
        try {
            post(logout_url, null, headers);
            System.out.println("退出登陆成功");
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 返回报文写入excel并格式化单元格
    public static void writeResult(String fileName, String sheetName, int row, int statusCodeColumn,
            int reponseContentColumn, int resultColumn,int responseKeyColumn, String excepedReponse,String responseKey) {
        try {
            ExcelUtil.writeData(fileName, sheetName, row, statusCodeColumn, String.valueOf(statusCode), null);
            ExcelUtil.writeData(fileName, sheetName, row, reponseContentColumn, reponseContent, null);
            // 如果返回包含預期輸入
            if (reponseContent.contains(excepedReponse)) {
                ExcelUtil.writeData(fileName, sheetName, row, resultColumn, "pass", "GREEN");
            } else {
                ExcelUtil.writeData(fileName, sheetName, row, resultColumn, "failed", "RED");
            }
            
            
            if (responseKey!=null) {
                String value=JsonUtil.getKeyValue(reponseContent, responseKey);
                ExcelUtil.writeData(fileName, sheetName, row, responseKeyColumn, value,null);
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    

}
View Code

ParasUtil.Java

package com.ygsoft.test.api;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.openxmlformats.schemas.wordprocessingml.x2006.main.impl.STTabTlcImpl;

public class ParasUtil {
    static String fileName;
    static String base_url;
    static String login_url;
    static String login_request;
    static String login_admin;
    static String logout_url;
    static String RealinsightAPI;
    static String etlAPI;

    public static void readParas(){
        try {
            ParasUtil.fileName=System.getProperty("user.dir")+"\datas\test.xlsx";
            System.out.println("接口文档路径 
"+ParasUtil.fileName);
            InputStream inStream = new FileInputStream(new File(System.getProperty("user.dir")+"\datas\Paras.properties"));
            Properties prop = new Properties();    
            prop.load(inStream);    
            ParasUtil.base_url=prop.getProperty("base_url");
            ParasUtil.login_url=prop.getProperty("login_url");
            ParasUtil.login_request=prop.getProperty("login_request");
            ParasUtil.login_admin=prop.getProperty("login_admin");
            ParasUtil.logout_url=prop.getProperty("logout_url");
            ParasUtil.RealinsightAPI=prop.getProperty("RealinsightAPI");
            ParasUtil.etlAPI=prop.getProperty("etlAPI");
            
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 
    }

    
}
View Code

JsonUtil.Java

package com.ygsoft.test.api;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonUtil {
    
    static List<String> keyValue=new ArrayList<>();
    
    // java递归遍历json对象,支持无限层级
    public static void analysisJson(Object objJson) {
        // 如果obj为json数组
        if (objJson instanceof JSONArray) {
            JSONArray objArray = (JSONArray) objJson;
            for (int i = 0; i < objArray.size(); i++) {
                analysisJson(objArray.get(i));
            }
        }
        // 如果为json对象
        else if (objJson instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) objJson;
            Iterator it = jsonObject.keys();
            while (it.hasNext()) {
                String key = it.next().toString();
                Object object = jsonObject.get(key);
                // 如果得到的是数组
                if (object instanceof JSONArray) {
                    JSONArray objArray = (JSONArray) object;
                    analysisJson(objArray);
                }
                // 如果key中是一个json对象
                else if (object instanceof JSONObject) {
                    analysisJson((JSONObject) object);
                }
                // 如果key中是其他
                else {
                    System.out.println("[" + key + "]:" + object.toString() + " ");
                }
            }
        }
    }

    // java递归遍历json对象,查看键值
    public static String getKeyValue(Object objJson, String test) {

        // 如果obj为json数组
        if (objJson instanceof JSONArray) {
            JSONArray objArray = (JSONArray) objJson;
            for (int i = 0; i < objArray.size(); i++) {
                getKeyValue(objArray.get(i), test);
            }
        }
        // 如果为json对象
        else if (objJson instanceof JSONObject) {
            JSONObject jsonObject = (JSONObject) objJson;
            Iterator it = jsonObject.keys();
            while (it.hasNext()) {
                String key = it.next().toString();
                Object object = jsonObject.get(key);
                // 如果得到的是数组
                if (object instanceof JSONArray) {
                    JSONArray objArray = (JSONArray) object;
                    getKeyValue(objArray, test);
                }
                // 如果key中是一个json对象
                else if (object instanceof JSONObject) {
                    getKeyValue((JSONObject) object, test);
                }
                // 如果key中是其他
                else {
//                    System.out.println("[" + key + "]:" + object.toString() + " ");
                    if (key.contains(test)) {
                        keyValue.add(object.toString());
                        break;
                    }
                }
            }
        }
        return keyValue.get(0);
    }
    
    
    public static String getKeyValue(String jsonStr, String test) {
        if (jsonStr.startsWith("{")) {
            JSONObject objJson = JSONObject.fromObject(jsonStr);
            return JsonUtil.getKeyValue(objJson, test);
        }else if(jsonStr.startsWith("[")){
             JSONArray jsonArray = JSONArray .fromObject(jsonStr);
              return JsonUtil.getKeyValue(jsonArray.toJSONObject(jsonArray), test);
        }else 
            return test;
        
    }
    
    /*
     * 递归遍历JSON对象。
     * 
     * @param JsonToMap
     * 
     * @return Map
     */
    public static Map<String, Object> IteratorHash(net.sf.json.JSONObject JsonToMap) {
        Iterator<?> it = JsonToMap.keys();
        HashMap<String, Object> RMap = new HashMap<String, Object>();

        while (it.hasNext()) {
            String key = String.valueOf(it.next());
            if (JsonToMap.get(key).getClass() == net.sf.json.JSONArray.class) {// 判是否为列表
                if (JsonToMap.getJSONArray(key).isEmpty()) {// 判列表是否为空
                    RMap.put(key, null);
                } else {

                    List<Map<String, Object>> MapListObj = new ArrayList<Map<String, Object>>();
                    for (Object JsonArray : JsonToMap.getJSONArray(key)) {
                        HashMap<String, Object> TempMap = new HashMap<String, Object>();
                        if (JsonArray.getClass() == String.class) {
                            TempMap.put(key, JsonArray);
                        } else {
                            TempMap.putAll(IteratorHash(net.sf.json.JSONObject.fromObject(JsonArray)));
                        }
                        MapListObj.add(TempMap);
                    }
                    RMap.put(key, (Object) MapListObj);
                }
            } else if (JsonToMap.get(key).getClass() == net.sf.json.JSONObject.class) {

                RMap.put(key, JsonToMap.getJSONObject(key));

            } else if (JsonToMap.get(key).getClass() == String.class || JsonToMap.get(key).getClass() == Integer.class
                    || JsonToMap.get(key).getClass() == Long.class) {

                RMap.put(key, JsonToMap.get(key));

            }
        }
        return RMap;
    }

}
View Code

  测试类

etlAPITest.Java

package com.ygsoft.test.api;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class etlAPITest extends HttpClientUtil {
    @BeforeClass
    public void loginTest() {
        readParas();
        login();
    }

    @Test
    public void etlAPITest() throws Exception {
        int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回状态码");
        int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回报文");
        int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "测试结果");
        int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值");
        
        List<Map<String, String>> result;
        headers.put("Authorization", Authorization);
        for (int i = 0; i < ExcelUtil.getRowNum(fileName, etlAPI); i++) {
            result = ExcelUtil.getTestData(fileName, etlAPI);
            System.out.println(result.get(i).get("请求类型") + "  " + result.get(i).get("请求头") + "  "
                    + result.get(i).get("测试要点") + "  " + result.get(i).get("输入"));
            headers.put("Content-Type", result.get(i).get("请求头"));
            if (result.get(i).get("请求类型").contains("POST")) {
                post(result.get(i).get("测试要点"), result.get(i).get("输入"), headers);
            } else if (result.get(i).get("请求类型").contains("GET")) {
                get(result.get(i).get("测试要点"),headers);
            } else if (result.get(i).get("请求类型").contains("UPLOAD")) {
                HashMap<String, String> header = new HashMap<String, String>();
                header.put("Authorization", Authorization);
                UploadFile(result.get(i).get("测试要点"), new File(result.get(i).get("输入")), header);
            }

            writeResult(fileName, etlAPI, Integer.parseInt(result.get(i).get("序号")), statusCodeColumn,
                    reponseContentColumn, resultColumn, responseKeyColumn, result.get(i).get("预期输出"),
                    result.get(i).get("返回键"));
        }
    }

    @AfterClass
    public void logoutTest() {
        logout();
    }
}
View Code

RealinsightAPITest.Java

package com.ygsoft.test.api;

import java.util.List;
import java.util.Map;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class RealinsightAPITest extends HttpClientUtil {
    @BeforeClass
    public void loginTest() {
        readParas();
        login_admin();
    }

    @Test
    public void RealinsightAPITest() throws Exception {
        int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回状态码");
        int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回报文");
        int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "测试结果");
        int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值");

        List<Map<String, String>> result;
        headers.put("Authorization", Authorization);
        for (int i = 0; i < ExcelUtil.getRowNum(fileName, RealinsightAPI); i++) {
            result = ExcelUtil.getTestData(fileName, RealinsightAPI);
            System.out.println(result.get(i).get("请求类型") + "  " + result.get(i).get("请求头") + "  "
                    + result.get(i).get("测试要点") + "  " + result.get(i).get("输入"));
            headers.put("Content-Type", result.get(i).get("请求头"));
            if (result.get(i).get("请求类型").contains("POST")) {
                post(result.get(i).get("测试要点"), result.get(i).get("输入"), headers);
            } else if (result.get(i).get("请求类型").contains("GET")) {
                get(result.get(i).get("测试要点"));
            }
            writeResult(fileName, RealinsightAPI, Integer.parseInt(result.get(i).get("序号")), statusCodeColumn,
                    reponseContentColumn, resultColumn, responseKeyColumn, result.get(i).get("预期输出"),
                    result.get(i).get("返回键"));
        }

    }

    @AfterClass
    public void logoutTest() {
        logout();
    }

    /*
     * @DataProvider(name = "test") public Object[][] dataMethod() throws
     * Exception { List<Map<String, String>> result; Object[][] files = new
     * Object[ExcelUtil.getRowNum(fileName, Sheet1)][]; for (int i = 0; i <
     * ExcelUtil.getRowNum(fileName, Sheet1); i++) {
     * result=ExcelUtil.getTestData(fileName, Sheet1); files[i] = new Object[] {
     * result.get(i) }; } return files; }
     */

    /*
     * @Test(dataProvider = "test") public void test(Map<String, String> param)
     * throws Exception { System.out.println( param.get("请求类型") +
     * "  "+param.get("请求头")+"  " + param.get("测试要点") + "  " + param.get("输入"));
     * headers.put("Authorization", Authorization); headers.put("Content-Type",
     * param.get("请求头")); if (param.get("请求类型").contains("POST")) {
     * post(param.get("测试要点"), param.get("输入"), headers); } else if
     * (param.get("请求类型").contains("GET")) { get(param.get("测试要点")); }
     * writeResult(fileName, Sheet1, Integer.parseInt(param.get("序号")), 12, 13,
     * 14,16, param.get("预期输出"),param.get("返回键")); }
     */

}
View Code

ClearResult.Java

package com.ygsoft.test.api;

import java.util.List;
import java.util.Map;

import org.testng.annotations.Test;

public class ClearResult extends HttpClientUtil {
    @Test
    public void f() throws Exception {
        readParas();
        List<Map<String, String>> result;
        int statusCodeColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回状态码");
        int reponseContentColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回报文");
        int resultColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "测试结果");
        int responseKeyColumn = ExcelUtil.getColumnNum(fileName, etlAPI, "返回值");

        for (int i = 0; i < ExcelUtil.getRowNum(fileName, etlAPI); i++) {
            result = ExcelUtil.getTestData(fileName, etlAPI);
            ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序号")), statusCodeColumn, null,
                    null);
            ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序号")), reponseContentColumn, null,
                    null);
            ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序号")), resultColumn, null, null);
            ExcelUtil.writeData(fileName, etlAPI, Integer.parseInt(result.get(i).get("序号")), responseKeyColumn, null,
                    null);
        }
    }
}
View Code
原文地址:https://www.cnblogs.com/gqhwk/p/12035930.html