Jmeter如何测试需要登录的接口

2023-12-23 17:52:26

首先说明本系统的登录采用的是session,但是无论是什么登录步骤都是大差不差的

1.首先要构造用户测试的数据保存到数据库
在这里插入图片描述

2.构造请求获取请求后的请求头(如果需要代码参照请看最后)
3.解析请求头获取需要的cookie(sessionId是放在cookie中)或token。如果对header的结果无法把控就打印一个看一下结构再解析
4.保存所有的cookie或token到一个txt文件中

在这里插入图片描述

5.接下来就是jmter的测试环节,最基本得有这几个
在这里插入图片描述
选择刚刚生成的cookie.txt文件
在这里插入图片描述

使用${}获取即可
在这里插入图片描述
接下来测试即可
在这里插入图片描述
所有代码

    /**
     * 登录接口示例
     */
    @PostMapping("/login")
    @ResponseBody
    public ResponseDTO userLogin(@Valid @RequestBody UserLoginReq req, HttpSession session, HttpServletRequest request) 
    @Test
    public void testCreateUserGetCookie() throws IOException {
        //1.创建测试用户集合信息,插入user表和student表
        List<TUserEntity> userEntityList = new ArrayList<>();
        List<TStudentEntity> studentEntityList = new ArrayList<>();
        //2.保存用户信息
        for (int i = 1; i <= 500; i++) {
            UUID uuid = UUID.randomUUID();
            String userId = uuid.toString().replaceAll("-", "");
            //user表
            TUserEntity userEntity = new TUserEntity();
            userEntity.setId(userId);
            userEntity.setRealName("user"+i);
            userEntity.setGender(1);
            userEntity.setUsername("123123"+i);
            userEntity.setPhoneNumber("130"+String.format("%0" + (11 - "130".length()) + "d", i));
            userEntity.setEmail("2080067852"+"@qq.com");
            userEntity.setPassword( CommonUtils.encodeByMd5(defaultPassword+salt));
            userEntity.setSchoolId("001");
            userEntity.setCampusId("0011");
            userEntity.setIcon("school.png");
            userEntity.setStatus(1);
            userEntity.setRecordStatus(1);
            userEntity.setKind(0);
            userEntity.setCreateTime(new Date());
            userEntityList.add(userEntity);
            //student表
            TStudentEntity tStudentEntity = new TStudentEntity();
            tStudentEntity.setSchoolId("001");
            tStudentEntity.setUserId(userId);
            tStudentEntity.setStudentNum("2015201805"+i);
            tStudentEntity.setName("张"+i+"憨");
            tStudentEntity.setGender(1);
            tStudentEntity.setCampus("test");
            tStudentEntity.setMajor("test");
            tStudentEntity.setClassNum("311631");
            tStudentEntity.setCreateTime(new Date());
            studentEntityList.add(tStudentEntity);
        }
        //3.批量保存
        studentService.saveBatch(studentEntityList);
        userService.saveBatch(userEntityList);
        //4.批量发起请求
        for (int i = 0; i < userEntityList.size(); i++) {
            //拼装参数发起请求,根据你自己的登录接口
            UserLoginReq userLoginReq = new UserLoginReq();
            userLoginReq.setUsername("123123"+(i+1));
            userLoginReq.setPassword("123456");
            userLoginReq.setSchoolId("001");
            userLoginReq.setCode("da513");
            String url="http://localhost:8080/api/v1/public/login";
            //发起请求,保存tokenn.txt文件
            sendHttpGetCookie(userLoginReq, url);
        }
    }
    private void sendHttpGetCookie(UserLoginReq userLoginReq, String url) throws IOException {
        // 2.创建Httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建Http Post请求
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
        //3.封装需要的数据
        String json = JSON.toJSONString(userLoginReq); // 将对象转换为 JSON 字符串
        StringEntity requestEntity = new StringEntity(json, StandardCharsets.UTF_8);
        httpPost.setEntity(requestEntity);
//        response = httpClient.execute(httpPost);
        //4.解析结果
        CloseableHttpResponse execute = httpClient.execute(httpPost);
        Header[] headers = execute.getAllHeaders();
        for (Header header : headers) {
            System.out.println(header.getName()+":"+header.getValue());
        }
        String value = headers[3].getValue();
        String cookie = value.split(";")[0];

        //2.写入文件
        File filePath=new File("D:/cookies.txt");
        FileWriter fileWriter = new FileWriter(filePath, true); // 使用 true 表示追加写入
        BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
        bufferedWriter.write(cookie);
        bufferedWriter.newLine(); // 换行
        // 关闭文件写入流
        bufferedWriter.close();
        System.out.println("cookieRes: "+cookie);
    }
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.13</version>
                <scope>compile</scope>
            </dependency>
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpmime</artifactId>
                <version>4.5.13</version>
                <scope>runtime</scope>
            </dependency>

文章来源:https://blog.csdn.net/qq_56533553/article/details/135141673
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。