项目实战——junit单元测试

项目准备:

jar包下载链接:

http://maven.aliyun.com/nexus/#welcome

本项目所需要的jar包:
mysql-connector-java-5.1.44.jar    数据库链接

gson-2.3.1.jar                          json数据的解析

备选:
json-lib-2.4-jdk15
json.jar
jsoup-1.10.3.jar

jsoup-1.8.1.jar

由于公司是上线接口,因此用junit执行测试用例的时候,需要通过HTTP协议发送接口请求,针对返回值进行断言处理。因此封装一个发送HTTP的方法。

Util包

public class HttpUtil {
        
        public static  int code = 0;
        //该方法返回的是String类型的json数据
        public static String getHttpContent(String temp,String parameterData ) throws Exception {
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
        try {
            URL address_url = new URL(temp);
            connection = (HttpURLConnection) address_url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("Accept-Charset", "utf-8");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", String.valueOf(parameterData.length()));
            connection.setRequestProperty("securityCheck", "******************");
            connection.setRequestProperty("os_type", "iOS");
            connection.setRequestProperty("app_version", "2.4.0");
            //设置访问超时时间及读取网页流的超市时间,毫秒值
            System.setProperty("sun.net.client.defaultConnectTimeout","3000");
            System.setProperty("sun.net.client.defaultReadTimeout", "3000");
            outputStream = connection.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);

            outputStreamWriter.write(parameterData);
            outputStreamWriter.flush();
            code = connection.getResponseCode();
            if (connection.getResponseCode() >= 300) {
               throw new Exception("HTTP Request is not success, Response code is " + connection.getResponseCode());
            }
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            System.out.println("-----------");
        }finally {
            if(connection !=null){
                connection.disconnect();
            }
        }
        return resultBuffer.toString();
    }
         
    /**
     * 向指定URL发送GET方法的请求
     * 
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     * @throws Exception 
     */
    public static String sendGet(String url) throws Exception {
        String result = "";
       // BufferedReader in = null;
       
            String urlNameString = url ;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
         
            code = ((HttpURLConnection) connection).getResponseCode();
            System.out.println(code);
        
        return result;
    }
        
}

由于接口路径包括传递的参数会发生改变,因此通过properties文件来解耦合。

/*
*filePath  --->properties文件全路径
*/
public class PropertiesUtil {
         //根据Key读取Value
    public static String GetValueByKey(String filePath, String key) {
        Properties pps = new Properties();
        try {
            InputStream in = new BufferedInputStream (new FileInputStream(filePath));  
            pps.load(in);
            String value = pps.getProperty(key);
         //   System.out.println(key + " = " + value);
            return value;
            
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}

test包

//通过映射获取properties文件的绝对路径
URL  url= getDetailById.class.getClassLoader().getResource("Url.properties");
String url_path =url.getPath();

//调用PropertiesUtil和HTTPUtil 获取jsonString

// 通过Gson 解析json 并封装实体类,获取实体类对象
         Gson gson = new Gson();
         getDetailByIdBean gdbib = gson.fromJson(json, getDetailByIdBean.class);
在网站上找到自动解析json创建实体类对象的工具

https://www.bejson.com/json2javapojo/

封装数据到实体类并通过Junit断言进行用例执行

junit详情参照:http://wiki.jikexueyuan.com/project/junit/using-assertion.html


因为很多数据要与实际数据库进行匹配,因此要进行数据库操作

创建数据库连接Util

public class DBUtil
{
  private static final String URL = "jdbc:mysql://localhost:3306/demo";
  private static final String UNAME = "root";
  private static final String PWD = "root";
 
  private static Connection conn = null;
 
  static
  {
    try
    {
      // 1.加载驱动程序
      Class.forName("com.mysql.jdbc.Driver");
      // 2.获得数据库的连接
      conn = DriverManager.getConnection(URL,UNAME,PWD);
    }
    catch (ClassNotFoundException e)
    {
      e.printStackTrace();
    }
    catch (SQLException e)
    {
      e.printStackTrace();
    }
  }
 
  public static Connection getConnection()
  {
    return conn;
  }
}

实际应用


以上就是单元测试的全部内容
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值