自动化框架Maven+TestNG+Java在测试体系中的应用(二)

2017-05-14  浮生若梦 

Maven+TestNg+Java框架的具体实现

环境要求需要自己安装mavenJava,这里不再赘述。我这边开发工具用的IDEA,大家可以根据自己的喜好选择。

基础服务创建与编码

新建项目,创建基础服务模块,我选择maven自动创建目录目录结构(maven-archetype-quickstart),因为是http协议这边需要引入http项目文件,模块pom引用内容如下:

IDEA可以根据引用的类明去寻找引入依赖,选择要引入的依赖文件就可以了。如图所示



选择要引用的项目,添加即可。家里网络原因没有搜索到包含类的项目,大家可以试验一下,我项目里边基本都这么引入依赖的。


Http请求代码实现如下:

public class HttpClientHelper {

    public HttpResponse methodPostHttpEntity(String url, HttpEntity httpEntity, boolean noNeedResponse) {

        //post请求返回结果

        HttpClient httpClient = new DefaultHttpClient();

        //10秒超时

        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000);

        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 10000);

        HttpResponse jsonResult = null;

        HttpPost method = new HttpPost(url);

        //设置post编码

        try {

            if (null != httpEntity) {

                method.setEntity(httpEntity);

//                System.out.println(EntityUtils.toString(method.getEntity(),"UTF-8"));

            }

//            method.setHeader("Content-Type","application/json");

            HttpResponse httpResponser = httpClient.execute(method);

            /**请求发送成功,并得到响应**/

            try {

                if (noNeedResponse) {

                    return null;

                }

                /**json字符串转换成json对象**/

                jsonResult = httpResponser;

            } catch (Exception e) {

                e.printStackTrace();

            }

        } catch (IOException e) {

            e.printStackTrace();

        }

        return jsonResult;

    }

    public HttpResponse methodPostStringEntity(String url, StringEntity stringEntity, boolean noNeedResponse) {

        HttpEntity httpEntity = stringEntity;

        HttpClientHelper httpClientHelper = new HttpClientHelper();

        return httpClientHelper.methodPostHttpEntity(url,httpEntity,noNeedResponse);

    }

    public HttpResponse methodPostParams(String url,Map params,boolean noNeedResponse){

        // 添加参数

        Listformparams = new ArrayList();

        for (Map.Entry entry:params.entrySet())

            formparams.add(new BasicNameValuePair(entry.getKey().toString(), entry.getValue().toString()));

        // 设置请求的编码格式

        HttpEntity httpEntity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);

        HttpClientHelper httpClientHelper = new HttpClientHelper();

        return httpClientHelper.methodPostHttpEntity(url,httpEntity,noNeedResponse);

    }

}

至此,基础模块编码完成。

接口自动化模块创建与编码

创建接口自动化模块,模块实现接口请求及响应编码自动化测试。

Pom引入基础服务和testNg,引用内容如下:


以登录为例实现整个过程

1.     准备全局配置数据

在setting包下创建配置默认数据

public class GlobalSetings {

    public static String baseUrl = "http://127.0.0.1/sevend/";

    public static String platform = "1";

    public static String lon = "113.922619";

    public static String bb="bb";

    public static String sign="cd9447162c1bb9faeba6423dfa6eb9d9";

    public static String t="1467257521";

    public static String network_type="WIFI";

    public static String imei="867600025565119";

    public static String appversion="3.8.0";

    public static String lat = "22.48735";

    public static String channel="anzhi_market";

    public static String os="6.0";

    public static String model="HUAWEI_MT7";


}

2.     编写登录接口API请求及数据响应

public class Login {


    public static JSONObject doLoginByHttpClientHelper(String mobile, String passWord){

        String verifyKey = "426006f9-22f2-4e2c-adaa-efe96ae51a87";

        String verifyCode = "1234";

        return Login.doLoginByHttpClientHelper(mobile,passWord,verifyKey,verifyCode);

    }


    public static JSONObject doLoginByHttpClientHelper(String mobile, String passWord,String verifyKey,String verifyCode){

        String fullUrl=GlobalSetings.baseUrl+"login";

        JSONObject response = new JSONObject();


        try {

            String pwd = new Encrypter().rsaEncrypt(passWord).toString();


            if(mobile.equals(null) || pwd.equals(null)) {

                response.put("error_msg","用户名或密码为空");

                return response;

            }


            JSONObject requestData = new JSONObject();

            //请求Head数据

            requestData.put("platform",GlobalSetings.platform);

            requestData.put("lon",GlobalSetings.lon);

            requestData.put("bb",GlobalSetings.bb);

            requestData.put("sign",GlobalSetings.sign);

            requestData.put("t",GlobalSetings.t);

            requestData.put("network_type",GlobalSetings.network_type);

            requestData.put("imei",GlobalSetings.imei);

            requestData.put("appversion",GlobalSetings.appversion);

            requestData.put("lat",GlobalSetings.lat);

            requestData.put("channel",GlobalSetings.channel);

            requestData.put("os",GlobalSetings.os);

            requestData.put("model",GlobalSetings.model);

            //请求Body数据

            requestData.put("mobile",mobile);

            requestData.put("pwd", pwd);

            requestData.put("verify_key", verifyKey);

            requestData.put("verify_code", verifyCode);


            HttpEntity httpEntity = new StringEntity(requestData.toString(), "UTF-8");

            HttpClientHelper httpClientHelper = new HttpClientHelper();

            HttpResponse httpResponse = httpClientHelper.methodPostHttpEntity(fullUrl,httpEntity,false);

            //响应状态判断

            if(httpResponse != null && httpResponse.getStatusLine().getStatusCode() != 200){

                return null;

            }

            //响应数据返回

            httpEntity = httpResponse.getEntity();

            if(httpEntity.equals(null)){

                return null;

            }else{

                response = JSONObject.fromObject(EntityUtils.toString(httpEntity,"UTF-8"));

            }


        } catch (Exception e) {

            response.put("code","800");

            response.put("error_msg",e.getMessage());

        }


        return response;

    }


}

我这里为了方便调用使用的是静态方法,当然为了不暴露方法可以使用非静态来调用。

3.     准备登录测试案例,实现登录套件

public class LoginSuit {


    public static JSONObject doLogin(String mobile, String passWord,String appVersion){

       //密码加密,需要替换为自己使用的加密算法

        String pwd = new Encrypter().rsaEncrypt(passWord).toString();

        JSONObject registResult = new JSONObject();

        if(mobile == null || mobile.equals(null) || passWord == null || passWord.equals(null)){

            registResult.put("code","10000");

            registResult.put("msg","缺少注册参数");

            return registResult;

        }


        JSONObject responseJson = new JSONObject();

        JSONObject responseData = new JSONObject();

        responseJson = Login.doLoginByStringEntity(mobile,pwd,appVersion);

//        System.out.print("response:"+responseJson);

        return responseJson;

    }


    @Test(dataProvider = "checkLogin",dataProviderClass = TestDataProvider.class,groups = "checkLogin")

    public static void getLogin(String mobile,String passWord,String exceptCode){

        JSONObject re = LoginSuit.doLogin(mobile,passWord,null);

        System.out.println(re.toString());

        Assert.assertEquals(re.get("code").toString(),exceptCode);

    }

}

4.     准备登录数据

public class TestData {

    //验证登录数据

    public static Object[] loginSuccess = {"15610000001","123456","0"};

    public static Object[] passwordError = {"15610000001","111111","3011"};

    public static Object[] mobileError = {"15610000000","111111","3002"};


}

public class TestDataProvider {

    @DataProvider(name = "checkLogin")

    public static Object[][] chedkLoginData(){

        return new Object[][] {TestData.loginSuccess,TestData.passwordError,TestData.mobileError};

    }

}

5.     运行测试套件,检验接口状态,出现下图信息说明接口已经调通

至此,整个自动化核心架构已经完成。其余工作就是将所有需要测试接口按项目按模块添加调试即可。

各包作用及如何串联

Com.dafy.autotest.sevend.api:实现需要做自动化的各个接口

Com.dafy.autotest.sevend.setings:服务固定参数的配置,例如数据库,服务url等

Com.dafy.autotest.sevend.testdata:用于初始化测试数据

Com.dafy.autotest.sevend.suit:功能流程实现与测试用例预期结果比对,用于判定接口功能实现正确性

整个架构的核心是suit,Suit实现各个接口调用及响应数据断言。通过@Test(dataProvider = "checkLogin",dataProviderClass = TestDataProvider.class,groups = "checkLogin")将测试数据与测试套件相关联。如此便通过数据驱动测试的执行。



TestNg这个框架包含很多内容,这两篇主要是依托testNg来构建接口测试的自动化,也就是给大家提供一个自动化的思路。关于TestNg的其他内容及教程可以搜索其他博主的文章学习。

182°|1820 人阅读|0 条评论
登录 后发表评论