主要内容:
如何构建http请求:指定http server地址,指定请求url
如何打印详细的请求信息
如何获取请求的响应状态码
在intellij上打开工程,java右键NewPackage:example
右键example新建一个java类:GetExample
实现GetExample类
引入相关类库:
import com.jayway.restassured.RestAssured;
import com.jayway.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.jayway.restassured.RestAssured.given;
测试case实现:
源码:
public class GetExample {
@BeforeClass
public void init(){
RestAssured.baseURI = "http://localhost:4567";
RestAssured.basePath = "/getTest"; }
@Test
public void getExampleTest(){
Response response = given().header("","").when().log().all().get("");
int resultCode = response.statusCode();
String result = response.getBody().print();
Assert.assertEquals(resultCode,200,"返回码错误!");
Assert.assertEquals(result,"get request is ok!","返回内容错误!");
}
}
解释说明:
@BeforeClass
public void init(){
RestAssured.baseURI = "http://localhost:4567";
RestAssured.basePath = "/getTest";
}
init方法配合testng的@BeforeClass annotation:
作用是运行测试之前先运行init方法。
我们再看init方法做了什么:
RestAssured.baseURI = "http://localhost:4567";RestAssured.basePath = "/getTest";
设置RestAssured的baseUR和basePath属性,看下RestAssured的源码:
按下ctrl键+左键点击“baseURI”来查看源码:
baseURI是string类型的静态变量,注释也解释的很清楚了,baseURI会作为默认的请求地址,通常就是请求接口的ip地址和端口号组合。
basePath同理查看,通常指请求接口的路径。
执行case,发送http请求:
Response response = given().header("","").when().log().all().get("");
关于请求头域的说明在后面的章节中再详细阐述,这里只实现简单的http请求
一个测试case只有执行部分,没有断言就不是完整的测试case,没有校验无法监控测试质量,断言部分的实现:
首先解析返回状态码和返回内容:
int resultCode = response.statusCode();String result = response.getBody().print();
使用testngAssert类库的断言方法:
Assert.assertEquals(resultCode,200,"返回码错误!");Assert.assertEquals(result,"get request is ok!","返回内容错误!");
assertEquals(实际结果,预期结果,如果实际结果和预期不相等时的提示信息)
assertNotNull(实际结果,实际结果为空时的提示信息)
运行测试case看看结果吧:
测试通过。