java 接口自动化

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

java 接口自动化_第1张图片
2、在jar文件同级目录下创建一个.json文件
java 接口自动化_第2张图片

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文件的名称

如果出现一下内容就是启动成功:
java 接口自动化_第3张图片
在浏览器中输入
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请求"
    }
  }
]

java 接口自动化_第4张图片
带参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"
      }
    }
  }
]

java 接口自动化_第5张图片

第一个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文件


<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.0modelVersion>

    <groupId>org.examplegroupId>
    <artifactId>chapter10artifactId>
    <version>1.0-SNAPSHOTversion>

    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.0.0.RELEASEversion>
    parent>

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponentsgroupId>
            <artifactId>httpclientartifactId>
            <version>4.5.13version>
        dependency>
        <dependency>
            <groupId>org.testnggroupId>
            <artifactId>testngartifactId>
            <version>7.6.1version>
        dependency>
        <dependency>
            <groupId>org.jsongroupId>
            <artifactId>jsonartifactId>
            <version>20170516version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

    dependencies>


project>

开发代码示例,运行后在浏览器输入http://localhost:8080/ 可以查看到内容hello world
java 接口自动化_第6张图片

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信息的接口开发
java 接口自动化_第7张图片
3&4携带cookies信息访问的get接口开发
java 接口自动化_第8张图片
5、携带参数get请求开发方式一
java 接口自动化_第9张图片
携带参数get请求开发方式二
java 接口自动化_第10张图片
7、返回cookie信息的post接口开发
java 接口自动化_第11张图片
java 接口自动化_第12张图片

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;
    }


}

你可能感兴趣的:(Java接口自动化,java,自动化,servlet)