javarestjunitresttemplatehttp-patch

How do I implement a PATCH executed via RestTemplate?


I am coding JUnit tests, calling my application via RestTemplate. I have successfully implemented GETs, POSTs, and PUTs, but can not get a PATCH to run (though it works when a client sends in the URL). A POST, for example, runs with this code:

    RestTemplate restTemplate = new RestTemplate(); 
    ProductModel postModel = restTemplate.postForObject(TestBase.URL + URL, pModel, ProductModel.class);            

But when I tried to call restTemplate.patchForObject() - which I found online - STS returns an error saying that function is not defined. I thus used this:

    RestTemplate restTemplate = new RestTemplate(); 
    ResponseEntity<MessageModel> retval = restTemplate.exchange("http://localhost:8080/products/batchUpdateProductPositions", 
            HttpMethod.PATCH, new HttpEntity<ProductPositionListModel>(pps), MessageModel.class);   

Which compiles, but gives me an error:

I/O Error on PATCH request for "http://localhost:8080/products/batchUpdateProductPositions": Invalid HTTP method: PATCH

In the application, I have the operation defined in a Controller class:

@RequestMapping(value = "/batchUpdateProductPositions", method = RequestMethod.PATCH)
public MessageModel batchUpdatePosition(
        @RequestBody ProductPositionListModel productPositionList)
        throws Exception {
    try {
        return productService.batchUpdatePosition(productPositionList);
    } catch (Exception e) {

I put a breakpoint on the return statement inside the 'try' block, but it never tripped when I ran it under debug.

Can anyone tell me where I tripped up?


Solution

  • I discovered a solution that stays consistent with the rest of the JUnit code. Using postForObject(), you can pass in the HTTP method you need in this case:

        MessageModel pModel = restTemplate.postForObject(TestBase.URL + URL + "/batchUpdateProductPositions?_method=patch", 
                pps, MessageModel.class);           
    

    This runs correctly. Couldn't say if there are side effects I'm not noticing.