1. 程式人生 > >(JAVA+TESTNG 三)Eclipse+TestNG搭建介面自動化測試框架

(JAVA+TESTNG 三)Eclipse+TestNG搭建介面自動化測試框架

轉載http://www.cnblogs.com/findyou/p/5388853.html

1、介面說明

例:北京市天氣

介面的址:http://www.weather.com.cn/data/cityinfo/101010100.html

  1. 請求方式:GET
  2. 請求結果:
{
    "weatherinfo": {
        "city": "北京",
        "cityid": "101010100",
        "temp1": "15℃",
        "temp2": "5℃",
        "weather": "多雲",
        "img1": "d1.gif",
        "img2": "n1.gif",
        "ptime": "08:00"
    }
}
問題:通過瀏覽器用get方法訪問介面地址,請求結果中文顯示亂碼。

解決方法:firefox,檢視-文字編碼-Unicode

2、測試目的

請求對應cityid程式碼,返回的城市是否是預期城市

3、JAVA工程

3.1.2 新建JAVA工程

步驟同上一篇2.2.2.1新建JAVA工程,不再複述,如不懂請百度Eclipse新建工程

1.工程結構說明

 

2.Common.java原始碼

package findyou.Interface;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

public class Common {
    /**
     * 解析Json內容
     * 
     * @author Findyou
     * @version 1.0 2015/3/23
     * @return JsonValue 返回JsonString中JsonId對應的Value
     **/

    public static String getJsonValue(String JsonString, String JsonId) {
        String JsonValue = "";
        if (JsonString == null || JsonString.trim().length() < 1) {
            return null;
        }

        try {
            JSONObject obj1 = new JSONObject(JsonString);
            JsonValue = (String) obj1.getString(JsonId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return JsonValue;
    }
}

JSONObject.getString()// 根據key返回一個字串

JSONObject.getInt()// 根據key返回一個整形資料

trim()方法返回呼叫字串物件的一個副本,但是所有起始和結尾的空格都被刪除了

Android中的JSON詳細總結 http://www.jb51.net/article/33414.htm

JSONObject與JSONArray的使用http://www.cnblogs.com/xwdreamer/archive/2011/12/16/2296904.html

JSON for java入門總結 http://blog.csdn.net/xiazdong/article/details/7059573

3.getCityWeathe.java原始碼

package findyou.Interface;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
public class getCityWeather {
    private String url="";    
    public String geturl() {
        return url;
    }

    public String getHttpRespone(String cityCode) throws IOException {
        String line = "";
        String httpResults = "";
        url=("http://www.weather.com.cn/data/cityinfo/"
                + cityCode + ".html");
        try {
            HttpURLConnection connection = URLConnection
                    .getConnection(url);
            DataOutputStream out = null;
            // 建立實際的連線
            connection.connect();
            out = new DataOutputStream(connection.getOutputStream());//建立一個新的資料輸出流,將資料寫入指定基礎輸出流。
            out.flush();//清空此資料輸出流,<span style="color:#0800;margin-top:0px; margin-right:0px; margin-bottom:0px; margin-left:0px; padding-top:0px; padding-right:0px; padding-bottom:0px; padding-left:0px; line-height:1.5;">重新整理物件輸出流,將任何位元組都寫入潛在的流中</span>out
            out.close();//
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            while ((line = reader.readLine()) != null) {
               httpResults = httpResults + line.toString();
            }
            reader.close();//關閉該流並釋放與之關聯的所有資源
            // 斷開連線
            connection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return httpResults;
    }
}

java.io類 DataOutputStream


          建立一個新的資料輸出流,將資料寫入指定基礎輸出流。

URLConnection類


          返回寫入到此連線的輸出流。

InputStreamReader 是位元組流通向字元流的橋樑

BufferedReader(Reader in)
建立一個使用預設大小輸入緩衝區的緩衝字元輸入流


          讀取一個文字行,(讀取時自動換行)

4.URLConnection.java原始碼

package findyou.Interface;
import java.net.HttpURLConnection;
import java.net.URL;
public class URLConnection {    
    public static HttpURLConnection getConnection(String url){
        HttpURLConnection connection = null;
        try {
            // 開啟和URL之間的連線
            URL postUrl = new URL(url);
            connection = (HttpURLConnection) postUrl.openConnection();
             // 設定通用的請求屬性
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestMethod("GET");
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Charset", "utf-8");
            connection.setRequestProperty("Accept-Charset", "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return connection;
    }
}

3.1.3 編寫測試用例


package findyou.testcase;

import java.io.IOException;

import org.testng.Assert;

import org.testng.Reporter;

import org.testng.annotations.Test;

import findyou.Interface.Common;

import findyou.Interface.getCityWeather;

public class test {

    public String httpResult= null, weatherinfo= null, city=null,exp_city = null;

    public static String cityCode="";

    getCityWeather weather=new getCityWeather();

    

    @Test(groups = { "BaseCase"})

    public void getShenZhen_Succ() throws IOException{

        exp_city="深圳";

        cityCode="101280601";

        resultCheck(cityCode, exp_city);

    }

    

    @Test(groups = { "BaseCase"})

    public void getBeiJing_Succ() throws IOException{

        exp_city="北京";

        cityCode="101010100";

        resultCheck(cityCode, exp_city);

    }

    

    @Test(groups = { "BaseCase"})

    public void getShangHai_Succ() throws IOException{

        exp_city="上海";

        cityCode="101020100";

        resultCheck(cityCode, exp_city);

    }

    

    public void resultCheck(String cityCode_str, String exp_city_str) throws IOException{

        Reporter.log("【正常用例】:獲取"+exp_city_str+"天氣成功!");

        httpResult=weather.getHttpRespone(cityCode_str);

        Reporter.log("請求地址: "+weather.geturl());

        Reporter.log("返回結果: "+httpResult);

        weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");

        city=Common.getJsonValue(weatherinfo, "city");

        Reporter.log("用例結果: resultCode=>expected: " + exp_city_str + " ,actual: "+ city);

        Assert.assertEquals(city,exp_city_str);        

    }

}