Empty respond body for post with rest assured

14,644

Solution 1

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);
}

Solution 2

This is where REST-Assured shines, its fluent interface is very helpful for locating the right method to use. If you're using Spring Boot, test should work without adding dependencies or configuration (except rest-assured, of course :)

Example controller

@RestController
@RequestMapping("/api")
public class Endpoints {

    public static class Assignment {
        public int id = 1;
        public String name = "Example assignment";
    }

    @RequestMapping(value = "/example",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<Assignment> example(@RequestBody Assignment assignment) {
        return ResponseEntity.created(URI.create("/example/1"))
                .body(assignment);
    }
}

and test:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration
@IntegrationTest("server.port:0")
public class EndpointsTest {

    @Autowired
    private ObjectMapper objectMapper;

    @Value("${local.server.port}")
    private int port;

    @Before
    public void setUp() {
        RestAssured.port = port;
    }

    @Test
    public void exampleTest() throws Exception {

        Endpoints.Assignment assignment =
            given()
            .contentType(ContentType.JSON)
            .body(objectMapper.writeValueAsBytes(new Endpoints.Assignment()))
        .when()
            .post("/api/example")
            .then().statusCode(HttpStatus.SC_CREATED)
            .extract().response()
            .as(Endpoints.Assignment.class);

        // We can now save the assignment.id
        assertEquals(1, assignment.id);
    }
}
Share:
14,644
Harshana
Author by

Harshana

Software Engineer (Specialized J2EE) based on Colombo Sri Lanka

Updated on July 20, 2022

Comments

  • Harshana
    Harshana almost 2 years

    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);
     }
    
  • Harshana
    Harshana over 8 years
    Thanks. I try using this. If i run with second body line it says, "no content-type was defined in the response". So then i add content type again as .then().statusCode(201).contentType("application/json") .body("assignmentId", equalTo("testid123")) but it says, application/json" doesn't match actual content-type. Any clue what the reason? In my controller the rest api produces and consumes attributes also defined as json. I have update my question to show how the controller api looks too.
  • Harshana
    Harshana over 8 years
    Also still when i inspect till peek(), i can see the content is null and contentType=""
  • Federico Piazza
    Federico Piazza over 8 years
    @Harshana I suspect your controller is not well configured. It might be generating xml instead of json if wrong headers are set, you maybe need to set up Accept header as json too. Besides that, I noticed use constant name without class you may use explicitly produces=MediaType.APPLICATION_JSON_VALUE. Additionally, before using RestAssured to connect to your service, ensure you can reach your controller with another client like Postman, and once you confirm it's working then move to RestAssured