2013-07-15 52 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"); 

}