问题
How to POST the below request using RestAssured in selenium.
The request is as follows:
{
"ShipmentID": "",
"ShipmentNumber": "123455-6",
"Comments": "",
"LineIDs": [
{
"ShipmentDID": "",
"AssetNum": "759585",
"FileC": "",
"SerialN": "",
"LineID": "5",
"Status": "Accept",
"TransferCancelComment": ""
}
Below is the code I have used but not sure how should i continue for the "LineID's" as it has few more attributes in it.
@Test
public void TransferIn() {
RestAssured.baseURI="testurl.rest.com";
RequestSpecification httpRequest = RestAssured.given();
JSONObject requestparams=new JSONObject();
try {
requestparams.put("ShipmentID", "");
requestparams.put("ShipmentNumber", "123455-6");
requestparams.put("Comments", "");
requestparams.put("LineIDs", "");
}
回答1:
Hope below code will solve your problem.
@Test
public void TransferIn() {
RestAssured.baseURI="testurl.rest.com";
RequestSpecification httpRequest = RestAssured.given();
JSONObject requestparams = new JSONObject();
JSONArray lineIdsArray = new JSONArray();
JSONObject lineIdObject = new JSONObject();
try {
requestparams.put("ShipmentID", "");
requestparams.put("ShipmentNumber", "123455-6");
requestparams.put("Comments", "");
lineIdObject.put("ShipmentDID", "");
lineIdObject.put("AssetNum", "759585");
lineIdObject.put("FileC", "");
lineIdObject.put("SerialN", "");
lineIdObject.put("LineID", "5");
lineIdObject.put("Status", "Accept");
lineIdObject.put("TransferCancelComment", "");
lineIdsArray.put(lineIdObject);
requestparams.put("LineIDs", lineIdsArray);
} catch (JSONException e) {
}
System.out.println(requestparams);
}
回答2:
A better approach could be, construct the json from a POJO/model file and then pass that to the test. By this, there is clear separation of the intent and in future if you want to verify any response of that type, you can simply de-serialize and get the values using getters of the POJO.
回答3:
e.g if your json is
{
"name":"Mohan",
"age":21
}
Your POJO would look something like below:
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
@SerializedName("name")
@Expose
private String name;
@SerializedName("age")
@Expose
private Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
I am using GSON from google which is serialization and de-serialization library. Construct your payload using your POJO and pass that as an argument to your test method. This will make your code more readable, maintainable, scalable ....
The idea behind this was the intent of test should not be polluted and there will be clear separation between the responsibilities of different entities.
来源:https://stackoverflow.com/questions/51245661/how-to-post-the-below-request-using-restassured-in-selenium