zoukankan      html  css  js  c++  java
  • http接口测试—自动化测试框架设计

    转载:https://my.oschina.net/hellotest/blog/499719

    一、测试需求描述

        对服务后台一系列的http接口功能测试。

        输入:根据接口描述构造不同的参数输入值(Json格式)

        输出:字符串(传入的方式+传入的字符串)

        http://localhost:8090/lctest/TestServer

    二、程序设计

        1、Client程序设计

            读取Excel配置的测试用例数据

            发送参数Json格式给Server,接收Server的返回数据

            进行数据比对校验,返回测试结果,将数据插入到Excel中

        2、Server端程序设计

            接受Client的参数,进行解析

            发送返回数据给client

    三、实现方法

        1、选用Java脚本来驱动测试

        2、采用Excel表格管理测试数据,包括用例的管理、测试数据录入、测试结果显示等等,这个需要封装一个Excel的类。

        3、调用http接口采用java自带的的API

        4、测试需要的将参数转化成字符串

        5、通过预期结果和实际结果的对比,将实际结果和对比结果写入Excel用例中,这里封装了一个类

        6、首次执行测试采用人工检查输出的是否正确,一旦正确写入Excel的期望结果中,如果发现错误手工修正为预期文件。

    四、Excel表格设计

    五、代码结构

    六、实现代码

    1、ExcelUtil.java

        

    package client;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFRichTextString;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    
    public class ExcelUtil {
    	
    	//读取Excel中数据
    	public static List<Param> read() throws Exception{
    		 HSSFWorkbook wb = new HSSFWorkbook();
    		 HSSFSheet s = wb.createSheet();
    		 HSSFRow row = s.createRow(0);
    		 HSSFCell cell = row.createCell((int)0,0);
    
    		 //------------从xls读出数据
    		 wb = new HSSFWorkbook(new FileInputStream("D:\learn\test.xls"));
    		 s = wb.getSheetAt(0);
    		 
    		 //获得EXCEL行数
    		 int rowNums=s.getLastRowNum();
    		 //获得Excell列数
    		 //int columnNum=r.getPhysicalNumberOfCells();
    		 
    		 List<Param> params=new ArrayList<Param>();
    		 for(int i=1;i<=rowNums;i++){
    			 HSSFRow r = s.getRow(i);
    			 cell=r.getCell(0);
    			 Param param= new Param();
    			 param.setNo(r.getCell(0).getStringCellValue());
    			 param.setName(r.getCell(1).getStringCellValue());
    			 param.setAge(r.getCell(2).getStringCellValue());
    			 param.setSex(r.getCell(3).getStringCellValue());
    			 param.setExpResu(r.getCell(4).getStringCellValue());
    //			 System.out.println(cell.getRichStringCellValue());
    			 params.add(param);
    		 }
    		 return params;
    
    	}
    
    	/**
    	  * 写入Excel,在任意坐标处写入数据。
    	  * String value:你要输入的内容
    	  * int x :行坐标,Excel从 0 算起
    	  * int y   :列坐标,Excel从 0 算起
    	  */
    		public static void writeCell(String filePath,int x,int y,String value) {
    			try {
    				// 创建Excel的工作书册 Workbook,对应到一个excel文档
    				HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(filePath));
    				HSSFSheet sheet=wb.getSheetAt(0);
    				HSSFRow row=sheet.getRow(x);
    				HSSFCell cell=row.getCell((short) y);
    				cell.setCellValue(value);
    				FileOutputStream os;
    				os = new FileOutputStream(filePath);
    				wb.write(os);
    				os.close();
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    
    		}
    }

    2、JsonsUtil.java

        

    package client;
    
    
    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    /**
     * 使用json-lib构造和解析Json数据
     */
    public class JsonsUtil {
    
        /**将Bean转换成Map
         * 将Map转换Json数据
         */public static String BuildJson(Param param) throws JSONException {
    
            
        	 Map<String, String> map1 = new HashMap<String, String>();
             map1.put("no", param.getNo());
             map1.put("name", param.getName());
             map1.put("age", param.getAge());
             map1.put("sex", param.getSex());
    //         map1.put("expResu", param.getExpResu());
        	 // JSON格式数据解析对象
            JSONObject jo = new JSONObject();
            // 将Map转换为JSONArray数据
            JSONArray ja = new JSONArray();
            ja.put(map1);
    //        System.out.println("JSONArray对象数据格式:"+ja.toString());
            jo.put("map", ja);
    //        System.out.println("最终构造的JSON数据格式:"+jo.toString());
            return jo.toString();
    
        }
    
        /**
         * 解析Json数据
         *
         */public static JSONArray ParseJson(String jsonString) throws JSONException,
                ParseException {
    
            JSONObject jo = new JSONObject(jsonString);
            JSONArray ja = jo.getJSONArray("map");
    //        System.out.println(ja.getJSONObject(0).getString("name"));
            return ja;
        }
    }

    3、Param.java

    package client;
    
    public class Param {
    	
    	String no;//编号
    	String name;//姓名
    	String age;//年龄
    	String sex;//性别
    	String expResu;//期望结果
    	String actResu;//实际结果
    	String pass;//是否通过
    	String desc;//描述
    	
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	
    	public String getNo() {
    		return no;
    	}
    
    	public void setNo(String no) {
    		this.no = no;
    	}
    
    	public String getAge() {
    		return age;
    	}
    
    	public void setAge(String age) {
    		this.age = age;
    	}
    
    	public String getSex() {
    		return sex;
    	}
    
    	public void setSex(String sex) {
    		this.sex = sex;
    	}
    
    	public String getExpResu() {
    		return expResu;
    	}
    
    	public void setExpResu(String expResu) {
    		this.expResu = expResu;
    	}
    
    	public String getActResu() {
    		return actResu;
    	}
    
    	public void setActResu(String actResu) {
    		this.actResu = actResu;
    	}
    
    	public String getPass() {
    		return pass;
    	}
    
    	public void setPass(String pass) {
    		this.pass = pass;
    	}
    
    	public String getDesc() {
    		return desc;
    	}
    
    	public void setDesc(String desc) {
    		this.desc = desc;
    	}
    }

    4、CompareRes.java

        

    package client;
    
    public class CompareRes {
    
    	int actResuNo=5;//测试结果在第五例
    	int passNo=6;//对比结果在第六列
    	
    	public  void compare(String filePath,Param param,String actResu){
    		
    		ExcelUtil.writeCell(filePath,Integer.parseInt(param.getNo()),actResuNo,actResu);
    		if(param.getExpResu().trim().equals(actResu)){
    			ExcelUtil.writeCell(filePath,Integer.parseInt(param.getNo()),passNo,"Y");
    		}else{
    			ExcelUtil.writeCell(filePath,Integer.parseInt(param.getNo()),passNo,"N");
    		}
    	}
    }

    5、TestClient .java

    package client;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.net.HttpURLConnection;
    import java.net.URL;
    import java.net.URLConnection;
    import java.util.List;
    
    public class TestClient {
    	
    	public static void main(String[]agrs){
    		TestClient a=new TestClient();
    		try {
    			a.client();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	public void client() throws Exception{
    		
    		List<Param> params = ExcelUtil.read();
    		for(Param pa:params){
    			try {
    				// 接报文的地址
    				String filePath="D:\learn\test.xls";
    				String param= new JsonsUtil().BuildJson(pa);
    				URL serverUrl= new URL("http://localhost:8090/lctest/TestServer");
    
    				URLConnection uct= serverUrl.openConnection();
    				HttpURLConnection hutc=(HttpURLConnection)uct;	
    				// 设置报文参数
    				hutc.setRequestMethod("POST");
    				
    				// 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在 http正文内,因此需要设为true, 默认情况下是false; 
    				hutc.setDoOutput(true);
    				
    				// 设置是否从httpUrlConnection读入,默认情况下是true
    				hutc.setDoInput(true);	
    //				hutc.setAllowUserInteraction(true);
    				
    				// 开启流,写入数据data
    				OutputStream out=hutc.getOutputStream();
    				
    				out.write(param.getBytes("UTF-8"));
    				out.flush();
    				out.close();
    				
    				// 获取返回的数据	
    				StringBuffer buffer=new StringBuffer();
    				BufferedReader reader = null;
    				InputStream ins=hutc.getInputStream();
    				reader = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
    				String sg=reader.readLine();
    				if (sg!= null){
    			           buffer.append(sg);
    			     }
    			        System.out.println("接收返回值:" + buffer);
    			        new CompareRes().compare(filePath, pa, buffer.toString());
    				
    				
    			} catch (Exception e) {
    				// TODO Auto-generated catch block
    				e.printStackTrace();
    			}
    		}
    		
    	
    	}
    }

    6、TestServer

    public class TestServer extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	 private static JSONArray ja;
           
        /**
         * @see HttpServlet#HttpServlet()
         */
        public TestServer() {
            super();
            // TODO Auto-generated constructor stub
        }
    
    	/**
    	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		try {
    			this.excute(request, response);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		try {
    			this.excute(request, response);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    	
    	public void excute(HttpServletRequest request,HttpServletResponse response) throws Exception{
    		request.setCharacterEncoding("utf-8");
    		response.setCharacterEncoding("UTF-8");
    		response.setContentType("text/xml");
    		String method=request.getMethod();
    		String url=request.getRequestURI();
    		String param;
    	       // 获取收到的报文
            BufferedReader reader = request.getReader();
            String line = "";
            line = reader.readLine();
            ja=new JsonsUtil().ParseJson(line);		
    		StringBuffer resultBuffer=new StringBuffer();
    		resultBuffer.append("访问方式"+method+"访问成功");
    		resultBuffer.append("接收到的数据:"+line);
    		PrintWriter out =response.getWriter();
    		out.println(resultBuffer.toString());
    		out.flush();
    		out.close();
    		
    	}
    }

    7、web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <servlet>
        <servlet-name>TestServer</servlet-name>
        <servlet-class>com.servlet.TestServer</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>TestServer</servlet-name>
        <url-pattern>/lctest/TestServer</url-pattern>
      </servlet-mapping>
    </web-app>
  • 相关阅读:
    net.sf.json.JSONException: There is a cycle in the hierarchy!
    数据源的配置
    java枚举使用详解
    hibernate级联保存,更新个人遇到的问题
    NonUniqueObjectException 问题
    No.2 dotnetcore&docker--数据库等在Docker上的配置
    No.1 dotnetcore&docker--环境搭建
    No.5 dotnetcore&docker--采用Ambry做文件服务器
    No.3 dotnetcore&docker--搭建一个nuget服务器
    关于APM数据采集实例以及Eureka整合的一个想法
  • 原文地址:https://www.cnblogs.com/ceshi2016/p/6603927.html
Copyright © 2011-2022 走看看