Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Empty respond body for post with rest assured

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);
 }
like image 231
Harshana Avatar asked Aug 14 '15 13:08

Harshana


2 Answers

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);
}
like image 192
Federico Piazza Avatar answered Sep 16 '22 13:09

Federico Piazza


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);
    }
}
like image 42
mzc Avatar answered Sep 20 '22 13:09

mzc