Empty respond body for post with rest assured

Harshana picture Harshana · Aug 14, 2015 · Viewed 11.8k times · Source

I am using restassured with junit4. In my test method i create a object in mongodb and when i run the test it successfully persist also. But i need to store the id created so i try to get the respond body. But the response.getBody().asString() is empty.

@Test
public void testA() throws JSONException {

    Map<String,Object> createVideoAssignmentParm = new HashMap<String,Object>();
    createVideoAssignmentParm.put("test1", "123");

    Response response = expect().statusCode(201).when().given().contentType("application/json;charset=UTF-8")
            .headers(createVideoAssignmentParm).body(assignment).post("videoAssignments");
    JSONObject jsonObject = new JSONObject(response.getBody().asString());
    id= (String)jsonObject.getString("assignmentId");
}

When i invoke the rest end point externally, it returns the response body also with relevant fields so no problem with the rest API.

If no answer for above question then how would you guys test a post with return body using rest assured so that i can try that way.

My controller method looks like,

 @RequestMapping(value = "/videoAssignment", produces = APPLICATION_JSON_VALUE, consumes = APPLICATION_JSON_VALUE, method = RequestMethod.POST)
 @ResponseBody
 public HttpEntity<VideoAssignment> createVideoAssingnment(
  //@ApiParam are there..){

    //other methods
    return new ResponseEntity<>(va, HttpStatus.CREATED);
 }

Answer

Federico Piazza picture Federico Piazza · Aug 17, 2015

We use a different wat to call services with RestAssured. However, if you get an empty string you can debug whether your service was called or not by using .peek().

You can use this test:

@Test
public void testStatus() 
{
    String response = 
            given()
               .contentType("application/json")
               .body(assignment)
            .when()
               .post("videoAssignments")
               .peek() // Use peek() to print the ouput
            .then()
                .statusCode(201) // check http status code
                .body("assignmentId", equalTo("584")) // whatever id you want
            .extract()
                .asString();

    assertNotNull(response);
}