0

How can I test the request json passed in restTemplate.postForEntity.

Lets say for the below method:

    void doAsyncCall(Int id){
        MyObject obj= mydao.getObject(id);
        ///do something 
        MyRequstObject myrequet = constructRequestfromObject(obj);// set some thing in request object form obj

        Myresponse resp = restTemplate.postForEntity(url,new 
        HttpEntitiy(myrequet), respone.class)

        if(resp.status==ok){
            Logger.log("done");
        }
   }

AND in My test case:-

I want to test whats being passed to the postForEntity method in request.

1) Its more like am I passing the correct Object and its properties to the post call.

2) Do we have any way of accessing request JSON in JUNIT to check the contract of what being passed

Please help.

Stin
  • 141
  • 1
  • 2
  • 12

1 Answers1

1

Mock the restTemplate in your test and call doAsyncCall and then verify if restTemplate.postForEntity is called with right parameter. To assert the object that is being passed to the method, you can you use ArgumentCaptor.capture(). For example:

    ArgumentCaptor<HttpEntity> captor = ArgumentCaptor.forClass(HttpEntity.class);

    verify(restTemplate).postForEntity(eq("some url"), captor.capture(), response.class);
    HttpEntity value = captor.getValue();
    assertEquals("content here", value.getContent());
Thiru
  • 2,541
  • 4
  • 25
  • 39