<dependency> <groupId>io.rest-assured</groupId> <artifactId>rest-assured</artifactId> <version>3.0.0</version> <scope>test</scope> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency>
@Before public void setup() { RestAssured.baseURI = "https://127.0.0.1:6443/as-api"; RestAssured.basePath = "/api/v1"; //單項認證容許全部客戶端經過 //RestAssured.useRelaxedHTTPSValidation(); }
Rest-Assured 能夠直接在 GET 的時候,同時進行驗證。以下例子:java
@Test public void test1() { given() .param("param", "1223434") .expect() .statusCode(200) .body("challenge", equalTo("1223434")) .when() .get("/test2"); }
或者這樣(是否是發現特別靈活,通常狀況下,經過一個鏈式調用就能夠完成一次API的測試git
get("/test2?param=1223434").then().body("challenge", equalTo("1223434"));
post請求github
@Test public void test() { Map<String, Object> map = new HashMap<>(); map.put("mode", 2); map.put("id", "23452345234"); map.put("identity", "11111111"); map.put("challenge", "s234523452345g"); map.put("response", "98CF0059D520E39E2016EB3AC70763BB26B665D77CD81378F11E5479E7094ACD"); map.put("sign", "1232321"); given() .contentType(ContentType.JSON) .request() .body(JSON.toJSONString(map)) .post("/test").then().assertThat() .body("mode", equalTo("2"),"id",equalTo("23452345234")).time(lessThan(1000L), TimeUnit.SECONDS); }
其中第一個body體是requestBody,第二個body是responseBody,並且能夠直接斷言相應body體裏面的內容是否是和本身預判的同樣。而且在特別狀況下還能夠檢測請求時間是否是超過咱們的預期。 文件上傳web
@Test public void testFile() { Response post = RestAssured.given() .given().param("id", "sdfgfsdg").multiPart("file1", new File("d:/pic.png")) .post("/apply/upload.do"); System.out.println(post.asString()); }
若是你是雙向認證只須要這樣一個鏈式調用就OK了,若是使用HttpUrlConention或者httpclient可不止這一行程序可以解決問題的,固然這並非說httpclient很差用,只能說,Rest-assured跟咱們提供了更好的封裝,下降咱們犯錯的概率,使我更高效率的投入到咱們業務中。api
RestAssured.authentication = RestAssured .certificate("clq.truststore", "123456","clq.p12", "123456", CertificateAuthSettings .certAuthSettings() .keyStoreType("PKCS12") .trustStoreType("jks"));
這裏只簡單列舉基於get和post以及HTTP(S)請求,從中能夠看出rest-assured的確語法簡單好用。 其中他還提供不少好用的API,例如操做頭部或者Cookie,或者在調用的過程種改變端口號等功能。這些咱們均可以根據API進行查找使用。 具體詳見測試用例源碼app