APP接口自动化测试JAVA+TestNG之HTTP接口测试实例

转自 http://www.cnblogs.com/findyou/p/5388853.html


目录

 

以下实例均为本次总结再次编写,,如转载还请保留出处与作者姓名Findyou,谢谢! 


3.1.1 待测接口说明

1.国家气象局天气预报接口

例:北京市天气

  1. 接口的址:http://www.weather.com.cn/data/cityinfo/101010100.html
  2. 请求方式:GET
  3. 请求结果:
复制代码
{
    "weatherinfo": {
        "city": "北京",
        "cityid": "101010100",
        "temp1": "15℃",
        "temp2": "5℃",
        "weather": "多云",
        "img1": "d1.gif",
        "img2": "n1.gif",
        "ptime": "08:00"
    }
}
复制代码

 

2.测试目标

请求对应cityid代码,返回的城市是否是预期城市。

 

 

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;
    }
}
复制代码

 

 

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();
            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;
    }
}
复制代码

 

 

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 编写测试用例

1.测试用例(常见"二"一般的写法)

复制代码
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="";    
     public  static getCityWeather weather= new getCityWeather();

    @Test(groups = { "BaseCase"})
     public  void getShenZhen_Succ()  throws IOException{
        exp_city="深圳";
        cityCode="101280601";
        Reporter.log("【正常用例】:获取"+exp_city+"天气成功!");
        httpResult=weather.getHttpRespone(cityCode);
        Reporter.log("请求地址: "+weather.geturl());
        Reporter.log("返回结果: "+httpResult);
        weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");
        city=Common.getJsonValue(weatherinfo, "city");
        Reporter.log("用例结果: resultCode=>expected: " + exp_city + " ,actual: "+ city);
        Assert.assertEquals(city,exp_city);
    }
    
    @Test(groups = { "BaseCase"})
     public  void getBeiJing_Succ()  throws IOException{
        exp_city="北京";
        cityCode="101010100";
        Reporter.log("【正常用例】:获取"+exp_city+"天气成功!");
        httpResult=weather.getHttpRespone(cityCode);
        Reporter.log("请求地址: "+weather.geturl());
        Reporter.log("返回结果: "+httpResult);
        weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");
        city=Common.getJsonValue(weatherinfo, "city");
        Reporter.log("用例结果: resultCode=>expected: " + exp_city + " ,actual: "+ city);
        Assert.assertEquals(city,exp_city);
    }
    
    @Test(groups = { "BaseCase"})
     public  void getShangHai_Succ()  throws IOException{
        exp_city="上海";
        cityCode="101020100";
        Reporter.log("【正常用例】:获取"+exp_city+"天气成功!");
        httpResult=weather.getHttpRespone(cityCode);
        Reporter.log("请求地址: "+weather.geturl());
        Reporter.log("返回结果: "+httpResult);
        weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");
        city=Common.getJsonValue(weatherinfo, "city");
        Reporter.log("用例结果: resultCode=>expected: " + exp_city + " ,actual: "+ city);
        Assert.assertEquals(city,exp_city);
    }    
}
复制代码

 

 

2.简化后的用例

如何返回值格式与请求格式固定,用例优化如下

 

复制代码
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);        
    }
}
复制代码

  

工程下载地址: http://pan.baidu.com/s/1mhyTNny 密码:11ft

 

 

3.1.4 执行测试用例

 

 


 

 

 TestNG自动化测试系列实例,基本已完毕,Post方法由于篇幅问题,则再不贴出来了,了解了以上实例,Post方法没有太大问题。后续如有时间看心情再上持续集成、自动化部署、自动化用例执行与测试报告输出博文
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
在进行接口自动化测试时,我们通常需要对接口进行请求并获取返回结果。而获取返回结果的方式一般有两种,一种是通过 HTTP 响应获取,另一种是通过解析 JSON 格式的响应体获取。 对于第一种方式,我们可以利用 Java 提供的 HttpURLConnection 类或者 Apache 的 HttpClient 库进行操作。而对于第二种方式,我们可以使用 JSON 解析库来解析响应体。 下面介绍通过 HttpURLConnection 获取响应体的方法: ```java import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpUtil { public static String doGet(String urlStr) { try { URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; StringBuilder result = new StringBuilder(); while ((line = in.readLine()) != null) { result.append(line); } in.close(); return result.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 上面的代码中,我们使用了 Java 提供的 HttpURLConnection 类来发送 GET 请求,并获取响应体。其中,URL 用于指定请求的地址,HttpURLConnection 用于建立与指定 URL 的连接,并发送请求。通过 BufferedReader 来读取响应体,并将其换为字符串返回。 使用该方法可以轻松地获取到接口返回的响应体。接下来,我们可以通过 JSON 解析库来解析响应体,从而获取接口返回的具体数据。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值