接口测试 新手入门 rest-assured 环境搭建

49875183 for rest-assured · 2016年12月12日 · 最后由 jiulingjushi 回复于 2018年09月24日 · 3364 次阅读

a) 新建一个 maven 项目

b) 在 pom.xml 添加相关依赖

<!--Rest assured依赖包-->
<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>rest-assured</artifactId>
      <version>3.0.1</version>
      <scope>test</scope><!--会发现我们自己建的类无法使用是因为设置了只在测试时使用用于编译和运行测试代码不会随项目发布删除<scope>后所有类都可使用-->
</dependency>
<!--独立Json path依赖包-->
<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>json-path</artifactId>
      <version>3.0.1</version>
</dependency>
<!--独立的Xml path依赖包-->
<dependency>
      <groupId>io.rest-assured</groupId>
      <artifactId>xml-path</artifactId>
      <version>3.0.1</version>
</dependency>

c) 新建一个测试类:

在类中引入相关 rest-assured 包:

import static io.restassured.RestAssured.*

官方建使用静态引入相关包,如果非静态方式引入,get()方法就会提示不存在,让你创建些方法。

d) 了解一些常用的请求设置

  • Cookie 设置

cookies(“name”,”testerhome”,”password”,”123456”,……)

cookie(“name”,”testerhome”).and().cookie(“password”,”123456”)

  • 代理设置

proxy("192.168.221.190",80)

  • 参数设置
Map<String, String> parameters = new HashMap<String, String>();
            parameters.put("pm", "2");
            parameters.put("a", "2");
            parameters(parameters);
parameters (parameters )

param("username", "John").and().param("password", "1234").

  • Header 头设置
Header first = new Header("username", "testerhome");
header(first)`

headers("username", "testerhome", "username1", "testerhome1")

e) 试着发起一个接口请求:

String url = "http://platform.app.autohome.com.cn/platform_v7.5.0/api/opt/propaganda";
    //设置入参
    Map<String, String> parameters = new HashMap<String, String>();
    parameters.put("pm", "2");
    parameters.put("a", "2");
    parameters.put("v", "7.6.0");
    parameters.put("deviceid", "7b64fb2877cbb15900b670886ea3f71488899c90");
 parameters.put("cityid", "110100");         
//设置url请求头
Header first = new Header("username", "xushizhao");
    Response response = given().proxy("192.168.221.190",80)
                .parameters(parameters)
                .header(first)
                .get(url);
//查看请求正文
System.out.println(response.asString());

f) 再了解一下 response 常用方法

方法 介绍
response.asString() 获取请求返回内容体
response.response.getContentType() 获取响应的内容类型
response.getStatusCode() 获取响应的状态代码
response.getHeaders() 获取所有响应头信息
response.getHeader(String name) 根据指定的 header 名称,获取对应的响应信息
response.getCookie(String name) 根据指定的 cookie 名称,获取对应 cookie 的值
response.getCookies() 获取所有 cookies 信息
response.getTime() 响应时间 (单位:毫秒)

rest-assured 的代码相对来说简洁明了,而且还提供了相应的断言机制json 验证以及封装了相关jsonpathxmlpath,使接口测试更加方便快捷,对接口测试感兴趣的小伙们可以试试~

相关使用我们会持续更新,欢迎大家一起来分享 rest-assured 相关知识,一起构造rest-assured相关节点~

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
共收到 18 条回复 时间 点赞

请教一下,如果是 post 请求,把 get 改为 post 是不是就可以了,Response response = given().params(parameters).post(url);

#4 楼 @cep 恩恩

是这样写的,Response response = given().contentType("application/json").params(parameters).post(url);
但是会报错:The request sent by the client was syntactically incorrect ()

Apache Tomcat/6.0.29 - Error report<!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}-->

HTTP Status 400 -


type Status report

message

description The request sent by the client was syntactically incorrect ().


Apache Tomcat/6.0.29

#6 楼 @cep application/json 参数序列化有问题吧

#6 楼 @cep 如果你想以 json 格式发送参数 ,使用这种方法

content
@Deprecated
RequestSpecification content(String content)
Deprecated. Use body(String) instead
Specify a String request content (such as e.g. JSON or XML) that'll be sent with the request. This works for the POST, PATCH and PUT methods only. Trying to do this for the other http methods will cause an exception to be thrown.
Example of use:

given().content("{ \"message\" : \"hello world\"}").then().expect().content(equalTo("hello world")).when().post("/json");

This will POST a request containing JSON to "/json" and expect that the response content equals to "hello world".
Note that body(String) and this method are the same except for the syntactic difference.

Parameters:
content - The content to send.
Returns:
The request specification

#8 楼 @xushizhao 徐老师请教下,如果 contentType 是 application/x-www-form-urlencoded 该怎么做呢?😅

徐校长,如果请求参数非 String 类型,比如 int 类型,如何传递参数呀?

#10 楼 @langmu
param(String, Object...)

param("string",1),param("string","1") 都可以的,一般情况下服务端会自动转换的,如果后端需求 int 类型,传了一个 abc123 这种类型的字符串才会转换错误

#11 楼 @xushizhao 那这个属于后台 bug 还是用例设计有误啊

#12 楼 @tspring

@ResponseBody
    @RequestMapping(value = "/getH5Status", produces = {"application/json;charset=utf-8"})
    public String getH5Status(HttpServletResponse response, HttpSession httpsession,
                       @RequestParam("H5PluginId") Integer H5PluginId ,@RequestParam("ciPluginId") Integer ciPluginId ) throws Exception {}

就拿这种方式来说,服务端对于 “1”、1 这种的传值都是接受的,服务端会自行转换,但是服务端要求的是Integer 当传 “1a”,"1.12" 这种类型的数据来说,肯定是转换失败的。

这和服务端使用的开发语言和框架有关系,这块建议和服务端开发确认一下,如果对于传入不正确的值需要服务端做验证并返回错误原因的,一般情况下需要单独提出这种诉求的。

服务端请求参数要求是 int ,如果传入 string 报错了,可以理解为服务端没做兼容处理,也可以理解为客户端调用不正确😁

对于服务端测试同学来说,就是为什么不按服务端规范调用,非法调用报错了,是正常现象啊😁

#13 楼 @xushizhao 传字符串” 1“时为什么使用 integer,不会保存,而是用 int 会报错? 是不是说如果是 String 1 可以自动完成 Integer 类型转换,而 int 不行。

#14 楼 @tspring
就拿这块来说,接口需要的是 int 类型的入参,使用进行 rest 调用时,参数是支持 OBJECT 类型,所以不管传 “1” 或 1 都是可以的,但服务端取值时,是以预先定义好的类型去获取的,在与服务端协定的类型一致的情况下,不管加不加"号都可以的

但是如果在浏览器中 http://localhost:8080/h5Interface/getH5Status?H5PluginId=1&ciPluginId=2’‘ 这么调用,明确给参数传入了字符串,这样是会报错的,但如果服务端是@RequestParam("H5PluginId") Object H5PluginId 这种类型的就无所谓了

@ResponseBody
    @RequestMapping(value = "/getH5Status", produces = {"application/json;charset=utf-8"})
    public String getH5Status(HttpServletResponse response, HttpSession httpsession,
                       @RequestParam("H5PluginId") Integer H5PluginId ,@RequestParam("ciPluginId") Integer ciPluginId ) throws Exception {}

given().param("H5PluginId", "1").and().param("ciPluginId", 2)
               .get("http://10.168.100.157:8080/h5Interface/getH5Status").getBody().prettyPeek();

Doris 回复

RestAssured.config = RestAssured.config().encoderConfig(encoderConfig().defaultCharsetForContentType("utf-8","application/x-www-form-urlencoded")); 可以设置 encoderconfig

老师,response.asString() 还是 text/html 格式,如何转换为 Json 格式打印?

官方建使用静态引入相关包,如果非静态方式引入,get()方法就会提示不存在,让你创建些方法,我是个初学者,遇到这种情况我该怎么解决呢,我现在搭建了环境,出现了这种情况

需要 登录 後方可回應,如果你還沒有帳號按這裡 注册