Java实现接口测试的实战练习

1.基本的结构



2.代码实现如下

Common.java

package findyou.Interface;
import org.codehaus.jettison.json.JSONException;//jason解析的方法
import org.codehaus.jettison.json.JSONObject;//jason解析的方法
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);//  以 Java 编程语言中 String 的形式获取此 ResultSet 对象的当前行中指定列的值
        } catch (JSONException e) {
            e.printStackTrace();在命令行打印异常信息在程序中出错的位置及原因。
        }
        return JsonValue;
    }

}

getCityWeather.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;


    }


}


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);//设置是否向httpUrlConnection输出
            connection.setDoInput(true);//设置是否从httpUrlConnection读入,默认情况下是true
            connection.setRequestMethod("GET");//设定请求的方法为"get"
            connection.setUseCaches(false);//是否可以使用缓存,Post 请求不能使用缓存
            connection.setInstanceFollowRedirects(true);//是否使用重定向
            connection.setRequestProperty("Content-Type", "application/json");//是否使用重定向
            connection.setRequestProperty("Charset", "utf-8");//(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) 
            connection.setRequestProperty("Accept-Charset", "utf-8");//
        } catch (Exception e) {
            e.printStackTrace();
        } 
        return connection;
    }

}


TestCase


RequestTest .java

package findyou.testcase;


import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStreamWriter;  
import java.net.URL;  
import java.net.URLConnection;  
import java.util.logging.Level;  
import java.util.logging.Logger;  
import org.apache.commons.io.IOUtils;  
  
public class RequestTest {  
    public static void main(String[] args){  
        try{  
            // Configure and open a connection to the site you will send the request  
            URL url = new URL("http://www.iana.org/domains/example/");  
            URLConnection urlConnection = url.openConnection();  
            // 设置doOutput属性为true表示将使用此urlConnection写入数据  
            urlConnection.setDoOutput(true);  
            // 定义待写入数据的内容类型,我们设置为application/x-www-form-urlencoded类型  
            urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");  
            // 得到请求的输出流对象  
            OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); 
            //OutputStreamWriter是Writer的子类,将输出的字符流变为字节流,即:将一个字符流的输出对象变为字节流的输出对象。
            //getOutputStream返回Servlet引擎创建的字节输出流对象
            
            // 把数据写入请求的Body  
            out.write("message = Hello World chszs");  
            out.flush();  
            out.close();  
              
            // 从服务器读取响应  
            InputStream inputStream = urlConnection.getInputStream();//  得到
            String encoding = urlConnection.getContentEncoding();  
            String body = IOUtils.toString(inputStream, encoding);  
            System.out.println(body);  
        }catch(IOException e){  
            Logger.getLogger(RequestTest.class.getName()).log(Level.SEVERE, null, e);  
        }  
    } 

test.java

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);//拼接url并且获得请求的URL
        Reporter.log("请求地址: "+weather.geturl());//输出地址
        Reporter.log("返回结果: "+httpResult);
        weatherinfo=Common.getJsonValue(httpResult, "weatherinfo");//将respose的内容转换成jason格式,然后截取部分内容(weatherinfo)
        city=Common.getJsonValue(weatherinfo, "city");//将respose的内容转换成jason格式,然后截取部分内容(weatherinfo)
        Reporter.log("用例结果: resultCode=>expected: " + exp_city_str + " ,actual: "+ city);//输出
        Assert.assertEquals(city,exp_city_str);        //实际截取的内容和输入的内容是否一致
    }
}

  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值