使用SpringBoot快速实现接口测试

SpringBoot是Java生态下的一个快速Web实现的微框架,最近使用它来实现对子系统接口的测试,这个系统仅仅是系统的一部分作为控制台来使用,其他还有两个系统,一个是从控制台获取Json格式的信息,处理后生成对外接口有两个,一个是提供给仓库,一个提供给SDK系统。对每一个接口的功能测试是从浏览器中访问 URL 地址来实现。

  1. 使用 Java 语言;
  2. 使用 JdbcTemplate 库访问Mysql;
  3. 使用 HttpClient
  4. 既有GET方法也有POST方法访问系统;POST访问前的数据封装需要注意,我这里使用 HttpEntity entity = new StringEntity(….)
    package me.code.controller;

    import com.alibaba.fastjson.JSON;
    import org.apache.http.HttpEntity;
    import org.apache.http.NameValuePair;
    import org.apache.http.client.entity.UrlEncodedFormEntity;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.message.BasicNameValuePair;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import shiver.me.timbers.data.random.RandomStrings;

    import java.io.IOException;
    import java.io.InputStream;
    import java.util.ArrayList;
    import java.util.List;

    /**
     * Created by wfan on 16/4/29.
     */

    @RestController
    @RequestMapping("/add")
    public class TestCustomAppInterface {
        @Autowired
        JdbcTemplate jdbcTemplate;

        RandomStrings randomStrings = new RandomStrings();
        String appName = randomStrings.someAlphaString(8);

        @RequestMapping("/app")
        public String addapp() throws IOException {
            //clean the table content first
            System.out.println("start to delete app table");
            String table = "victoria_custom_app";
            this.cleanDBTableContent(table);
            int num = getCountFromTable(table);
            if (0 == num)
                System.out.println("clean app table successfully!");
            else
                System.out.println("failed to clean app table !");

            CloseableHttpClient httpClient = HttpClients.createDefault();
            String factorIds = "1,20,21,22,23,24,20,1,21,22,23,24,";
            String uri = "http://localhost:9090/addCustomApp?appid=" + appName + "&factorIds=" + factorIds;
            HttpGet httpGet = new HttpGet(uri);
            CloseableHttpResponse response = httpClient.execute(httpGet);

            String getHeader = null;
            response.getHeaders(getHeader);

            System.out.println("Header info is : " + getHeader);

            //return getHeader;
            InputStream inputStream = null;
            inputStream = response.getEntity().getContent();

            boolean isEmpty = this.getInfoByAppName(table, appName, factorIds);
            int status = response.getStatusLine().getStatusCode();
            if (isEmpty)
                System.out.println("ERROR : FAIL TO ADD CUSTOM APP NAME ! ");
            else if (!isEmpty && 200==status)
                System.out.println("ADD NEW APP NAME SUCCESSFULLY ! ");

            //TODO FOR LOG
            return "response content is " + inputStream.toString() + "\n" + "  status is  "
                    + response.getStatusLine().getStatusCode()
                    + "  appname is " + appName
                    + " number is after call clean function " + num;
        }

        @RequestMapping("/rule")
        public String addRule() throws IOException{
            cleanDBTableContent("victoria_custom_rule");
            int ruleCount = getCountFromTable("victoria_custom_rule");
            if (0 == ruleCount)
                System.out.println("clean rule table successfully!");
            else
                System.out.println("failed to clean rule table !");

            CloseableHttpClient httpClient = HttpClients.createDefault();
            String curAppName = appName;
            //String ruleValue = "[{'description':'undefined', 'subsidy_score':'0.06', 'negative_complaints_score':'-0.02'}]";
            String uri = "http://localhost:9090/saveCustomRules?app=" + curAppName;//+ "&object=" + ruleValue;
            HttpPost httpPost = new HttpPost(uri);

            //List<NameValuePair> nvps = new ArrayList<NameValuePair>();

    //        nvps.add(new BasicNameValuePair("\"description", "undefined1"));
    //        nvps.add(new BasicNameValuePair("subsidy_score", "0.06"));
    //        nvps.add(new BasicNameValuePair("nagative_complaints_score", "-0.02"));

            HttpEntity entity= new StringEntity("[{\"tea_exposure_score\":\"0\",\"negative_reminder_score\":\"-0.01\",\"exposure_score\":\"0\",\"negative_bad_rating_score\":\"-0.02\",\"dinner_exposure_score\":\"0\",\"rid\":1,\"description\":\"undefined\"}]","utf-8");
            httpPost.setEntity(entity);

            CloseableHttpResponse response = httpClient.execute(httpPost);

            return "use app name is " + curAppName
                    + "response content is " + response.getEntity().getContent()
                    + " response status is " + response.getStatusLine().getStatusCode();
        }

        @RequestMapping("/case")
        public String saveCases() throws Exception{
            String testName;
            String testDate = "2016-05-04%2000:00%20-%202016-05-04%2023:59";
            int status[] = string2ASCII("编辑中");

            //delete a record from case table

            /*String delstr = "delete from victoria_test_case where object=\"芜湖\"";
            jdbcTemplate.execute(delstr);*/

            RandomStrings randomStrings = new RandomStrings();
            testName = randomStrings.someAlphaString(6);

            CloseableHttpClient httpClient = HttpClients.createDefault();
            String uri = "http://localhost:9090/saveCases?testName=" + testName + "&testDate=" + testDate + "&status=" + status;
            HttpPost httpPost = new HttpPost(uri);
            HttpEntity entity = new StringEntity("[{\"description\":\"234\",\"id\":1,\"object\":\"芜湖\",\"rule_id\":\"1\",\"sample_weight\":\"12%\"}]","utf-8");
            httpPost.setEntity(entity);
            CloseableHttpResponse response = httpClient.execute(httpPost);

            return "response status is " + response.getStatusLine().getStatusCode();
        }

        public void cleanDBTableContent(String tableName) throws IOException{
            String sql = "delete from " + tableName;

            jdbcTemplate.execute(sql);
        }

        public int getCountFromTable(String tableName){
            //String sql = "select count(*) from " + tableName;
            String sql = "select * from " + tableName;
            List re = jdbcTemplate.queryForList(sql);
            return re.size();
        }

        public boolean getInfoByAppName(String tableName, String appName, String factors){
            String sql = "select * from " + tableName + " where app_name = " + "\"" + appName + "\" " +
                    "and factor_ids = " + "\"" + factors +"\"";

            List re = jdbcTemplate.queryForList(sql);

            return re.isEmpty();
        }


        public static String gbEncoding(final String gbString) {
            char[] utfBytes = gbString.toCharArray();
            String unicodeBytes = "";
            for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
                String hexB = Integer.toHexString(utfBytes[byteIndex]);
                if (hexB.length() <= 2) {
                    hexB = "00" + hexB;
                }
                unicodeBytes = unicodeBytes + "\\u" + hexB;
            }
            System.out.println("unicodeBytes is: " + unicodeBytes);
            return unicodeBytes;
        }

        public static String decodeUnicode(final String dataStr) {
            int start = 0;
            int end = 0;
            final StringBuffer buffer = new StringBuffer();
            while (start > -1) {
                end = dataStr.indexOf("\\u", start + 2);
                String charStr = "";
                if (end == -1) {
                    charStr = dataStr.substring(start + 2, dataStr.length());
                } else {
                    charStr = dataStr.substring(start + 2, end);
                }
                char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
                buffer.append(new Character(letter).toString());
                start = end;
            }
            return buffer.toString();
        }

        public static int[] string2ASCII(String s) {// 字符串转换为ASCII码
            if (s == null || "".equals(s)) {
                return null;
            }

            char[] chars = s.toCharArray();
            int[] asciiArray = new int[chars.length];

            for (int i = 0; i < chars.length; i++) {
                asciiArray[i] = char2ASCII(chars[i]);
            }
            return asciiArray;
        }
        public static int char2ASCII(char c) {
            return (int) c;
        }
    }
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值