接口自动化落地(二:HttpClient+testNG实现对接口的测试及校验)

接口自动化落地(一:MySQL+MyBatis实现对测试用例数据的读取)中已经实现了基础配置和测试用例数据准备,本篇文章将以登录举例进行测试执行。

这是之前login接口的代码

@Test(groups = "loginTrue",description = "用户登录接口测试")
    public void loginTrue() throws IOException {
        SqlSession session = DatabaseUtil.getSqlsession();
        LoginCase loginCase = session.selectOne("loginCase",1);
        System.out.println(loginCase.toString());
        System.out.println(TestConfig.loginUrl);
    }

接下来只需要进行两步:1.发送请求 2.验证返回结果

//第一步发送请求
String result = getResult(loginCase);
//第二步验证返回结果
Assert.assertEquals(loginCase.getExpected(),result);

getResult方法被我抽离出来了放在下面,原因是无论我是登录成功,或者登录失败,等会执行相同的操作,只是测试数据和校验部分会不一样。
这是getResult方法的具体代码:

private String getResult(LoginCase loginCase) throws IOException {
        HttpPost post = new HttpPost(TestConfig.loginUrl);
        //设置body部分
        JSONObject param = new JSONObject();
        param.put("userName",loginCase.getUserName());
        param.put("password",loginCase.getPassword());

        //设置header部分信息
        post.setHeader("content-type","application/json");

        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);

        //测试执行
        String result;
        HttpResponse response  = TestConfig.defaultHttpClient.execute(post);
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println(result);

        TestConfig.store = TestConfig.defaultHttpClient.getCookieStore();

        return result;
    }

获取的结果会返回到result中,然后与mysql中存的预期值loginCase.getExpected()进行对比,如结果一样则测试通过。
这里写图片描述

猜你喜欢

转载自blog.csdn.net/lt326030434/article/details/80706696