2013-07-15 34 views
1

我在其餘的保證代碼中有以下郵寄請求:使用Rest Assured的參數化郵寄請求有效負載

我想參數化它。請建議。

 given().contentType(JSON).with() 
      .body("\"id\":"123",\"email\":\"[email protected]\"}").expect().body("status",    
     notNullValue()).when().post("https://localhost:8080/product/create.json"); 

參數

ID,電子郵件。

當我聲明字符串變量ID,電子郵件和嘗試傳遞身體()它不工作。

不工作代碼:

String id="123"; 
String [email protected]; 

given().contentType(JSON).with() 
    .body("\"id\":id,\"email\":email}").expect().body("status",    
    notNullValue()).when().post("https://localhost:8080/product/create.json"); 
+0

也許並不重要,但一個大括號似乎在你的身體開始失蹤。 –

+0

對不起,我錯過了提供。但仍然有問題。 – dileepvarma

+1

意外地低估了你。我已將其標記爲主持人關注。希望他們能夠撤消它,因爲我沒有注意到我已經做到了,我的撤銷時間已經過期。 – Andrew

回答

3

在身上我們需要給像精確的字符串:

"{\"id\":" + id + ",\"email\":" + email + "}" 

這應該工作。但這不是最好的方法。你應該考慮創建一個包含2個字段(id和email)的類,並且作爲請求的主體,你應該添加對象的json序列化主體。

LoginRequest loginRequest = new LoginRequest(id, email); 
String loginAsString = Util.toJson(loginRequest); 
given().contentType(JSON).with() 
    .body(loginAsString)... 

試試這個方法。
希望它有幫助。

+0

如何支持或處理嵌套參數? – OverrockSTAR

0

除了使用POJO還可以使用一個HashMap

given(). 
     contentType(JSON). 
     body(new HashMap<String, Object>() {{ 
      put("name", "John Doe"); 
      put("address", new HashMap<String, Object>() {{ 
       put("street", "Some street"); 
       put("areaCode", 21223); 
      }}); 
     }}). 
when(). 
     post("https://localhost:8080/product/create.json") 
then(). 
     body("status", notNullValue()); 
0

發送的字符串帶有大量參數的可能變得乏味和更新具有參數n個可能變得費時的字符串。因此,總是建議使用body方法發送一個對象。

我勸你去通過我的休息教程一步一步放心:

Automating POST Request using Rest Assured

看一看下面的例子

public class Posts { 

public String id; 
public String title; 
public String author; 

public void setId (String id) { 

this.id = id; 
} 

public void setTitle (String title) { 

this.title = title; 
} 

public void setAuthor (String author) { 

this.author = author; 

} 

public String getId() { 

return id; 

} 

public String getTitle() { 

return title; 
} 

public String getAuthor() { 

return author; 
} 

} 

在上面的Post類,我們有創建了我們需要傳遞給body方法的參數的getter和setter方法。

現在,我們將發送POST請求

import org.testng.Assert; 
import org.testng.annotations.BeforeClass; 
import org.testng.annotations.Test; 
import static com.jayway.restassured.RestAssured.* 
import com.jayway.restassured.RestAssured; 
import com.jayway.restassured.http.ContentType; 
import com.jayway.restassured.response.Response; 
import com.restapiclass.Posts; 

public class PostRequestTest { 


@BeforeClass 
public void setBaseUri() { 

RestAssured.baseURI = "http://localhost:3000"; 
} 


@Test 
public void sendPostObject() { 

Posts post = new Posts(); 
post.setId ("3"); 
post.setTitle ("Hello India"); 
post.setAuthor ("StaffWriter"); 

given().body (post) 
.when() 
.contentType (ContentType.JSON) 
.post ("/posts"); 

} 
相關問題