java 接口自动化

第7章mock平台功能介绍
1、moco框架,下载standalone.jar,最大的包
https://repo1.maven.org/maven2/com/github/dreamhead/moco-runner/1.0.0/

在这里插入图片描述
2、在jar文件同级目录下创建一个.json文件
在这里插入图片描述

3、test.json内容必须是一个数组([])开头,内部是json格式,一个json就等于一个请求。如果有多个请求就创建多个json,都是放在数组里面,基本格式:

moco响应信息会乱码,需要在响应信息头加上: “Content-Type”:“text/html;charset=gbk”。

description:接口的说明,给自己看的。

response:请求的信息。

uri:接口的路径。

method:方法类型

json:请求需要传的参数。

headers:设置请求头。

response:设置响应的信息。

text:响应的内容,这个只能返回文本,不能返回json。

json:设置响应内容为json格式的数据。

headers:响应的头,例如: “Content-Type”:“text/html;charset=gbk”。

这是一个简单的moco示例

[
  {
    "description":"这是一个mock测试的接口",
    "request":{
      "uri":"/demo",
      "method":"get"
    },
    "response":{
      "text":"这是mock响应的结果"
    }
  }
]

4、在dos命令行输入:java -jar moco-runner-1.0.0-standalone.jar http -p 8888 -c mockTest.json

java -jar mocojar的名称 http -p 端口-c json文件的名称

如果出现一下内容就是启动成功:
在这里插入图片描述
在浏览器中输入
http://127.0.0.1:8888/demo或
http://localhost:8888/demo,可以成功访问

在这里插入图片描述
5、带参get

[
  {
    "description":"这是一个mock测试的接口",
    "request":{
      "uri":"/getdemo",
      "method":"get"
    },
    "response":{
      "text":"这是无参数的get请求"
    }
  },
  {
    "description":"这是一个带参的get请求",
    "request":{
      "uri":"/getwithparam",
      "method":"get",
      "queries": {
        "name": "lily",
        "age": "18"
      }
    },
    "response":{
      "text":"这是带参数的get请求"
    }
  }
]

在这里插入图片描述
带参post

[
  {
    "description":"这是一个post请求",
    "request":{
      "uri":"/postdemo",
      "method":"post"
    },
    "response":{
      "text":"这是mock的post请求"
    }
  },

  {
    "description":"这是手机号错误的接口",
    "request":{
      "uri":"/loginPhoneError",
      "method":"post",
      "headers":{
        "Content-Type":"application/json"
      },
      "json":{
        "phone":"15519094256",
        "password":"osm6762955"
      }
    },
    "response":{
      "json":{
        "msg":"手机号或密码错误",
        "code":500,
        "data":null
      },
      "headers":{
        "Content-Type":"text/html;charset=utf-8"
      }
    }
  }
]

在这里插入图片描述

第一个demo

public class MyHttpClient {

    public static void main(String[] args) throws IOException {
        //用来存放结果
        String result;
        HttpGet get = new HttpGet("Http://www.baidu.com");
        HttpClient httpClient = HttpClients.createDefault();
        HttpResponse httpResponse = httpClient.execute(get);
        System.out.println("响应"+httpResponse);
        //获取响应结果
        result = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
        System.out.println("响应result"+result);
    }
}

携带cookies信息访问get请求

import org.apache.http.HttpResponse;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.testng.annotations.Test;

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

public class MyCookieForGet {
    //用来存储cookies变量
    private CookieStore store;
    @Test
    public void cookies() throws IOException {
        //用来存放结果
        String result;
        HttpGet get = new HttpGet("Http://www.baidu.com");
        DefaultHttpClient client = new DefaultHttpClient();
        CloseableHttpResponse response = client.execute(get);
        //获取响应状态码
        System.out.println(response.getStatusLine().getStatusCode());

        //获取响应结果
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("响应result"+result);

        //获取cookies信息
        this.store = client.getCookieStore();
        List<Cookie> cookieList = store.getCookies();
        for (Cookie cookie : cookieList) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name:"+name);
            System.out.println("cookie value:"+value);
        }
        System.out.println("======");
    }
    @Test(dependsOnMethods = {"cookies"})
    public void testGetWithCookies() throws IOException {
        HttpGet get = new HttpGet("Http://www.baidu.com/xxx");
        DefaultHttpClient client = new DefaultHttpClient();
        //设置cookie信息
        client.setCookieStore(this.store);

        CloseableHttpResponse response = client.execute(get);
    }
}

携带cookies访问post请求

import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
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.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import org.testng.annotations.Test;

import java.io.IOException;
import java.util.List;
import java.util.ResourceBundle;

public class MyCookiesForPost {
    private String url;
    private ResourceBundle bundle;
    //用来存储cookies变量
    private CookieStore store;
    @Test
    public void BeforeTest(){
        bundle= ResourceBundle.getBundle("application.properties");
        url=bundle.getString("test.url");
    }
    @Test
    public void cookies() throws IOException {
        //用来存放结果
        String result;
        HttpGet get = new HttpGet("Http://www.baidu.com");
        DefaultHttpClient client = new DefaultHttpClient();
        CloseableHttpResponse response = client.execute(get);
        //获取响应状态码
        System.out.println(response.getStatusLine().getStatusCode());

        //获取响应结果
        result = EntityUtils.toString(response.getEntity(),"utf-8");
        System.out.println("响应result"+result);

        //获取cookies信息
        this.store = client.getCookieStore();
        List<Cookie> cookieList = store.getCookies();
        for (Cookie cookie : cookieList) {
            String name = cookie.getName();
            String value = cookie.getValue();
            System.out.println("cookie name:"+name);
            System.out.println("cookie value:"+value);
        }
        System.out.println("======");
    }
    @Test(dependsOnMethods = {"cookies"})
    public void testPostMethod() throws IOException {
        String uri=bundle.getString("test.post.with.cookies");
        //拼接最终的测试地址
        String testUrl = this.url + uri;
        //声明一个Client对象,用来进行方法的执行
        DefaultHttpClient client = new DefaultHttpClient();
        //声明一个方法,就是post方法
        HttpPost post = new HttpPost(testUrl);
        //添加参数
        JSONObject param = new JSONObject();
        param.put("name","xiaowang");
        param.put("age","18");
        //设置请求头信息
        post.setHeader("content-type","application/json");
        //将参数添加到方法中
        StringEntity entity = new StringEntity(param.toString(),"utf-8");
        post.setEntity(entity);
        //声明一个对象来进行响应结果的存储
        String result;
        //设置cookies信息
        client.setCookieStore(this.store);
        //执行post方法
        CloseableHttpResponse response = client.execute(post);
        //获取响应结果
        result = EntityUtils.toString(response.getEntity(), "utf-8");
        //处理结果,转化为json字符串
        JSONObject resultJson = new JSONObject(result);
        //判断结果
        String status = (String)resultJson.get("status");
    }
}

第10章,springBoot 简介及官方demo开发
1、配置pom文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>chapter10</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>7.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20170516</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

    </dependencies>


</project>

开发代码示例,运行后在浏览器输入http://localhost:8080/ 可以查看到内容hello world
在这里插入图片描述

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@EnableAutoConfiguration
public class SimpleController {
    @RequestMapping("/")
    @ResponseBody
    String home(){
        return "hello world";
    }

    public static void main(String[] args) {
        SpringApplication.run(SimpleController.class,args);
    }

}

2、返回cookies信息的接口开发
在这里插入图片描述
3&4携带cookies信息访问的get接口开发
在这里插入图片描述
5、携带参数get请求开发方式一
在这里插入图片描述
携带参数get请求开发方式二
在这里插入图片描述
7、返回cookie信息的post接口开发
在这里插入图片描述
在这里插入图片描述

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.course.server")
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args);
    }
}

package com.course.server;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
public class MyGetMethod {

    @RequestMapping(value = "/getCookies",method = RequestMethod.GET)
    public String getCookies(HttpServletResponse response){
        Cookie cookie = new Cookie("login", "true");
        response.addCookie(cookie);
        return "恭喜你获得cookies信息";
    }

    /**
     * 要求客户端携带cookies访问
     */
    @RequestMapping(value = "get/with/cookies",method = RequestMethod.GET)
    public String getWithCookies(HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        if (Objects.isNull(cookies)){
            return "需要携带cookies";
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("login")&&cookie.getValue().equals("true")){
                return "携带cookies访问成功";
            }
        }
        return "必须携带cookies信息来";
    }

    /**
     * 开发一个需要携带参数才能访问的get请求
     * 第一种实现方式url:key=value&key=value
     */
    @RequestMapping(value = "/get/with/param",method = RequestMethod.GET)
    public Map<String,Integer> getList(@RequestParam Integer start, @RequestParam Integer end){
        HashMap<String, Integer> myList = new HashMap<>();
        myList.put("鞋",400);
        myList.put("面",1);
        myList.put("T shirt",200);
        return myList;
    }

    /**
     * 第二种携带参数访问的get请求
     * url:ip:port//get/with/param/10/20
     */
    @RequestMapping(value = "/get/with/param/{start}/{end}",method = RequestMethod.GET)
    public  Map myGetList(@PathVariable Integer start,@PathVariable Integer end){
        HashMap<String, Integer> myList = new HashMap<>();
        myList.put("鞋",400);
        myList.put("面",1);
        myList.put("T shirt",200);
        return myList;
    }
}

package com.course.server;

import com.course.bean.User;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("v1")
public class MyPostMethod {

    //这个变量用来装cookies信息
    private static Cookie cookie;
    //用户登录成功获取cookies,然后在访问其他接口
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public  String login(HttpServletResponse response,
                         @RequestParam(value = "userName",required = true) String userName,
                         @RequestParam(value = "password",required = true) String password){
        if (userName.equals("zhangsan")&&password.equals("123456")){
            Cookie cookie = new Cookie("login","true");
            response.addCookie(cookie);
            return "恭喜登录成功";
        }
        return "用户名或密码错误";
    }

    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    public User getUserList(HttpServletRequest request,@RequestBody User u){
        User user;
        //获取cookies
        Cookie[] cookies = request.getCookies();
        //验证cookies是否合法
        for (Cookie c : cookies) {
            if (c.getName().equals("login") && c.getValue().equals("true")
            && u.getUsername().equals("zhangsan")&& u.getPassword().equals("123456")){
                user = new User();
                user.setName("lisi");
                user.setAge("18");
                user.setSex("man");
                return user;
            }
        }
        return null;
    }


}

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java接口自动化框架是一种用于自动化测试Java接口的工具或框架。它可以帮助开发人员或测试人员更有效地进行接口测试。有一些常见的Java接口自动化框架可供选择,其中一些包括: 1. RestAssured:这是一个流行的Java库,用于进行RESTful接口测试。它提供了丰富的API来发送请求,验证响应和解析JSON/XML响应。 2. TestNG:这是一个灵活的测试框架,可以用于Java接口的自动化测试。它提供了一些强大的功能,如测试套件的组织,数据驱动和并发执行。 3. Spring Boot:这是一个全面的Java开发框架,它也提供了一些工具和功能,用于进行接口测试。它具有良好的整合性和易于使用的特点。 4. Junit:这是一个广泛使用的Java单元测试框架,在接口测试中也可以使用。它提供了一些注解和断言方法,方便进行测试和验证。 尽管使用Python编写接口自动化框架可能会增加代码编写量,但这并不意味着Python对于Java接口自动化框架是不合适的。实际上,Python也是一种流行的语言,可以用于编写自动化测试脚本。最终的选择可能取决于项目的具体需求,团队的技术栈和偏好。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Java接口自动化测试框架系列(一)自动化测试框架](https://blog.csdn.net/m0_75277660/article/details/130143492)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Java接口自动化测试框架](https://blog.csdn.net/qq_38503984/article/details/103167878)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值