Say,
I have a method getTemplateData() and I want to mock a restTemplate.exchange() method call in that
public List<String> getTemplateData(String templateId, String storeId, String projectId) {
RestTemplate restTemplate = new RestTemplate();
Map<String, String> bodyObject = new HashMap<>();
bodyObject.put("functionalAreaId", templateId);
bodyObject.put("storeId", storeId);
bodyObject.put("projectId", projectId);
HttpEntity<?> requestEntity = new HttpEntity<>(bodyObject, null);
ResponseEntity<List<String>> result =
restTemplate.exchange(
BaseUrl + "/template",
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<List<String>>() {});
List<String> screens = result.getBody().stream().collect(Collectors.toList());
log.info(
"Completed executing the method getTemplateData for the templateId:{} and storeId:{}",
templateId,
storeId);
return screens;
}
I want to mock the line
ResponseEntity<List<String>> result =
restTemplate.exchange(
BaseUrl + "/template",
HttpMethod.POST,
requestEntity,
new ParameterizedTypeReference<List<String>>() {});
Is it possible to mock a statement in Java?
Yes, that can be mocked.
#Test
public void test() {
// let's create mock first, you can use annotation also
RestTemplate mockTemplate = Mockito.mock(RestTemplate.class);
Mockito.when(mockTemplate.exchange(Mockito.eq(BaseUrl + "/template"),
Mockito.eq(HttpMethod.POST),
Mockito.eq(requestEntity),
Mockito.any(ParameterizedTypeReference.class))
.thenReturn(new ResponseEntity<>(Arrays.asList("data"), HttpStatus.OK))
}
Related
I'm currently working on a Spring Boot CRUD RESTful API with an User entity that consists of two parameters : name and id. Its endpoints are :
POST REQUEST IN /users - Create an user
GET REQUEST IN /users/{id} - List a specific user by its id
GET REQUEST IN /users - List all users
PUT REQUEST IN /users/{id} - Update a specific user by its id
DELETE REQUEST IN /users/{id} - Delete a specific user by its id
Each endpoint is built with a controller and a service to implement its logic.
I've already wrote unit tests for my controllers and services, now i'm trying to build integration tests to assert that my endpoints work properly as a group of components.
No mocking involved, all this will be done by using the TestRestTemplate and asserting that every operation was executed correctly and every response checked with its expected value.
The following are the tests I've already built :
#SpringBootTest(classes = UsersApiApplication.class,
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class UserControllerTest {
#LocalServerPort
private int port;
TestRestTemplate restTemplate = new TestRestTemplate();
HttpHeaders headers = new HttpHeaders();
private void instantiateNewUser() {
User userNumberFour = new User();
userNumberFour.setName("Four");
userNumberFour.setId(4L);
ResponseEntity<User> responseEntity = restTemplate
.postForEntity(createURLWithPort("/users"), userNumberFour, User.class);
}
#Test
public void createNewUserTest() {
User testUser = new User();
testUser.setName("Test User");
testUser.setId(5L);
ResponseEntity<User> responseEntity = restTemplate
.postForEntity(createURLWithPort("/users"), testUser, User.class);
assertEquals(201, responseEntity.getStatusCodeValue());
assertEquals(responseEntity.getBody(), testUser);
}
#Test
public void listSpecificUserTest() throws JSONException {
instantiateNewUser();
HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
createURLWithPort("/users/4/"),
HttpMethod.GET, httpEntity, String.class);
String expectedResponseBody = "{id:4,name:Four}";
assertEquals(200, responseEntity.getStatusCodeValue());
JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
}
#Test
public void listAllUsersTest() throws JSONException {
instantiateNewUser();
HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
createURLWithPort("/users"),
HttpMethod.GET, httpEntity, String.class);
//All instantiated users
ArrayList<String> expectedResponseBody = new ArrayList<>(Collections.emptyList());
expectedResponseBody.add("{id:1,name:Neo}");
expectedResponseBody.add("{id:2,name:Owt}");
expectedResponseBody.add("{id:3,name:Three}");
expectedResponseBody.add("{id:4,name:Four}");
assertEquals(200, responseEntity.getStatusCodeValue());
JSONAssert.assertEquals(String.valueOf(expectedResponseBody), responseEntity.getBody(), false);
}
#Test
public void deleteSpecificUserTest() throws JSONException {
instantiateNewUser();
HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
createURLWithPort("/users/4/"),
HttpMethod.DELETE, httpEntity, String.class);
assertEquals(204, responseEntity.getStatusCodeValue());
JSONAssert.assertEquals(null, responseEntity.getBody(), false);
}
private String createURLWithPort(String uri) {
return "http://localhost:" + port + uri;
}
}
As you can see, it's missing the PUT request method test, which is the update endpoint.
To implement its logic, i need to send a message body with the content that will override the old users characteristics, but how?
This is what i made so far :
#Test
public void updateSpecificUserTest() throws JSONException {
instantiateNewUser();
HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
createURLWithPort("/users/4/"),
HttpMethod.PUT, httpEntity, String.class);
String expectedResponseBody = "{id:4,name:Four Updated}";
assertEquals(200, responseEntity.getStatusCodeValue());
JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
}
Would appreciate if someone could help with this one, didn't found the answer online.
HttpEntity<String> httpEntity = new HttpEntity<String>(null, headers);
You have sent body as null. Also you can use mockMvc it is better approach then rest template.
User testUser = new User();
testUser.setName("Test User");
HttpEntity<String> httpEntity = new HttpEntity<String>(testUser, headers);
https://howtodoinjava.com/spring-boot2/testing/spring-boot-mockmvc-example/
So, the solution to my problem really was that I was sending a null request body in my httpEntity.
I also needed to set the content type to JSON :
#Test
public void updateSpecificUserTest() throws JSONException, JsonProcessingException {
instantiateNewUser();
User updatedUser = new User();
updatedUser.setName("Updated");
updatedUser.setId(4L);
ObjectMapper mapper = new ObjectMapper();
String requestBody = mapper.writeValueAsString(updatedUser);
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<String> responseEntity = restTemplate.exchange(
createURLWithPort("/users/4/"),
HttpMethod.PUT, httpEntity, String.class);
String expectedResponseBody = "{id:4,name:Updated}";
assertEquals(200, responseEntity.getStatusCodeValue());
JSONAssert.assertEquals(expectedResponseBody, responseEntity.getBody(), false);
}
I am using RestTemplate postForEntity method to post body to an endpoint. I need help with writing test case for my code using Mockito. The return type is void but it can be changed to Types or code if needed to test. I have referred many other documentation but they are very general, I tried using them but most did not work for me as the request and return type are different. . Any suggestions are appreciated. Thank you
Here is my Java class
public void postJson(Set<Type> Types){
try {
String oneString = String.join(",", Types);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", oneString);
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
}
}
You are testing the logic inside MyClass class, so you should not mock it. RestTemplate is a dependency inside MyClass, so this is exactly what you need to mock. In general it should look like this inside your test:
This is just a simple example. A good practice would be to check that the arguments passed to your mock equal to the expected ones. One way would be to replace Mockito.eq() with the real expected data. Another is to verify it separately, like this:
public ResponseEntity<String> postJson(Set<Type> Types){
try {
String oneString = String.join(",", Types);
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", oneString);
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<String>(jsonObject.toString(), null);
ResponseEntity result = restTemplate.exchange(url, HttpMethod.POST,
new HttpEntity<>(request, getHttpHeaders()), String.class);
}
}
return Types;
You can write test for above method as follows
#Mock
RestTemplate restTemplate;
private Poster poster;
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), getHttpHeaders());
ResponseEntity<String> result = restTemplate.exchange(uri, HttpMethod.POST, request, String.class);
Mockito.verify(restTemplate, Mockito.times(1)).exchange(
Mockito.eq(uri),
Mockito.eq(HttpMethod.POST),
Mockito.eq(request),
Mockito.eq(String.class));
Assert.assertEquals(result, poster.postJson(mockData));
HttpHeaders getHttpHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.add(// whatever you need to add);
return headers;
}
Here is my solution to this problem, but it requires some changes.
First of all, you have to externalize the RestTemplate as a bean and add converters in its initialization. This way you will get rid of not covering those converters.
#Bean
public RestTemplate restTemplate() {
RestTemplate restTemplate = new RestTemplate();
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
restTemplate.getMessageConverters().add(jsonConverter);
StringHttpMessageConverter stringConverter = new StringHttpMessageConverter();
restTemplate.getMessageConverters().add(stringConverter);
return restTemplate;
}
Here's the new class that contains postJson method. As you can see, the url and restTemplate are injected through the constructor. This way we can test different cases.
public class Poster {
private RestTemplate restTemplate;
private String url;
public Poster(RestTemplate restTemplate, String url) {
this.restTemplate = restTemplate;
this.url = url;
}
public void postJson(Set<Type> types) {
try {
String oneString = types.stream().map(Type::toString).collect(Collectors.joining(","));
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", oneString);
requestBody.put("data", "aws");
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);
ResponseEntity<String> result = restTemplate
.postForEntity(url, new HttpEntity<>(request, getHttpHeaders()), String.class);
int code = result.getStatusCodeValue();
} catch (Exception ignored) {}
}
private HttpHeaders getHttpHeaders() {
return new HttpHeaders();
}
}
And here's the test class for that method.
class PosterTest {
#Mock
private RestTemplate restTemplate;
private String url;
private Poster poster;
#BeforeEach
public void setUp() {
MockitoAnnotations.initMocks(this);
this.url = "http://example.com/posturl";
this.poster = new Poster(restTemplate, url);
}
#Test
void postJson() {
// set input, I used TreeSet just to have a sorted set
// so that I can check the results against
Set<Type> types = new TreeSet<>(Comparator.comparing(Type::toString));
types.add(new Type("a"));
types.add(new Type("b"));
types.add(new Type("c"));
types.add(new Type("d"));
// response entity
ResponseEntity<String> response = ResponseEntity.ok("RESPONSE");
// mockito mock
Mockito.when(restTemplate.postForEntity(
ArgumentMatchers.eq(url),
ArgumentMatchers.any(HttpHeaders.class),
ArgumentMatchers.eq(String.class)
)).thenReturn(response);
// to check the results
Map<String, String> requestBody = new HashMap<>();
requestBody.put("type", "a,b,c,d");
requestBody.put("data", "aws");
JSONObject jsonObject = new JSONObject(requestBody);
HttpEntity<String> request = new HttpEntity<>(jsonObject.toString(), null);
HttpEntity<HttpEntity<String>> httpEntity = new HttpEntity<>(request, new HttpHeaders());
// actual call
poster.postJson(types);
// verification
Mockito.verify(restTemplate, times(1)).postForEntity(
ArgumentMatchers.eq(url),
ArgumentMatchers.eq(httpEntity),
ArgumentMatchers.eq(String.class));
}
}
It is better to have the dependencies like RestTemplate or other ServiceClasses so that they can be mocked and tested easily.
A while back, I wrote about unit testing and test doubles. You can have a read as a starting point on how to approach unit testing.
Some of it's key take aways are:
Test Behaviour not Implementation. Tests that are independent of implementation details are easier to maintain. In most cases, tests should focus on testing your code’s public API, and your code’s implementation details shouldn’t need to be exposed to tests.
The size of the unit under test is discretionary but the smaller the unit, the better it is.
When talking about unit tests, a more quintessential distinction is whether the unit under test should be sociable or solitary.
A test double is an object that can stand in for a real object in a test, similar to how a stunt double stands in for an actor in a movie. They are test doubles not mocks. A mock is one of the test doubles. Different test doubles have different uses.
It's hard to write a whole test as a lot of information is missing. E.g. what Type is.
As you did not posted the name of your class I'm just name it MyClass for now.
Also I'm assuming that the RestTemplate is injected via the constructor like
MyClass(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
Following is a draft for a unit test using JUnit 5 and Mockito.
I would suggest mocking the RestTemplate. I have to admit that this way we will not cover to test the usage of MappingJackson2HttpMessageConverter and StringHttpMessageConverter in our test.
So a very raw draft could look like this
import java.util.ArrayList;
import java.util.Set;
import org.junit.Assert;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.http.HttpEntity;
import org.springframework.web.client.RestTemplate;
class MyClassTest {
private RestTemplate restTemplate;
private MyClass myClass;
#BeforeEach
void setUp() {
restTemplate = Mockito.mock(RestTemplate.class);
myClass = new MyClass(restTemplate);
}
#Test
void callMethod() {
Set<Type> types = Set.of(/* one of your Types */);
String url = "http://someUrl";
String httpResult = "";
Mockito.when(restTemplate.getMessageConverters()).thenReturn(new ArrayList<>());
ArgumentCaptor<HttpEntity> request = ArgumentCaptor.forClass(HttpEntity.class);
Mockito.when(restTemplate.postForObject(url, request.capture(), String.class)).thenReturn(httpResult);
myClass.callMethod(types, url);
HttpEntity<String> actualHttpEntity = request.getValue();
Assert.assertEquals(actualHttpEntity.getBody(), "");
}
}
Relevant Code Below:
ServiceCode:
#Override
public ResponseEntity<AppointmentResponse> createAppointment(AppointmentRequest partnerFulfillmentRequest) {
RestTemplate rt = null;
ResponseEntity<AppointmentResponse> response = null;
String uri = null;
HttpEntity<AppointmentRequest> httpEntity = null;
HttpHeaders headers = null;
try {
rt = new RestTemplate();
rt.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
rt.getMessageConverters().add(new StringHttpMessageConverter());
uri = new String(internalServiceUrl+"/"+APP_NAME_INTERNAL+"/appointment");
log.info("Calling internal service URL : "+uri);
headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
httpEntity = new HttpEntity<AppointmentRequest>(partnerFulfillmentRequest, headers);
response = rt.exchange(uri, HttpMethod.PUT, httpEntity, AppointmentResponse.class);
if (response != null)
{
log.info("Got response from internal servicec-->statusCode: "+response.getStatusCodeValue());
log.info("Got response from internal service--> Body "+response.getBody());
}
}catch(HttpClientErrorException hceEx) {
//hceEx.printStackTrace();
AppointmentResponse res = new AppointmentResponse();
return new ResponseEntity<AppointmentResponse>(mapResponse(hceEx.getResponseBodyAsString()), hceEx.getResponseHeaders(), hceEx.getStatusCode());
}catch(Exception e) {
e.printStackTrace();
AppointmentResponse res = new AppointmentResponse();
ResponseEntity<AppointmentResponse> wfmErrResponse = new ResponseEntity<AppointmentResponse>(res, HttpStatus.INTERNAL_SERVER_ERROR);
log.error("ERROR WHILE CALLING INTERNAL SERVICE");
log.error(uri);
log.error(e);
return wfmErrResponse;
}
return response;
}
Test Code:
#RunWith(MockitoJUnitRunner.class)
public class PartnerFulfillmentServiceImplTest {
#Mock
RestTemplate restTemplate;
#Mock
HttpHeaders httpHeaders;
#Mock
ResponseEntity responseEntity;
#InjectMocks
PartnerFulfillmentServiceImpl partnerFulfillmentService;
#Test
public void createAppointmentTest() {
Whitebox.setInternalState(partnerFulfillmentService, "internalServiceUrl", "http://localhost:8080");
AppointmentRequest appointmentRequest = new AppointmentRequest();
appointmentRequest.setPartnerName("CENTRICITY");
appointmentRequest.setTicketNumber("123ABC");
httpHeaders = new HttpHeaders();
httpHeaders.set("Content-type", "application/json");
responseEntity = new ResponseEntity<>(
"some response body",
HttpStatus.OK
);
when(restTemplate.exchange(Mockito.anyString(),
Mockito.<HttpMethod> any(),
Mockito.<HttpEntity<?>> any(),
Mockito.<Class<Object>> any()))
.thenReturn(responseEntity);
ResponseEntity<AppointmentResponse> response = partnerFulfillmentService.createAppointment(appointmentRequest);
Assert.assertEquals(response.getStatusCode(), HttpStatus.OK);
}
}
I'm getting
java.lang.AssertionError:
Expected :500
Actual :200
and understandably so because it is not actually calling running .thenReturn(responseEntity); logic. My million dollar question is, why? It should be returning the responseEntity value. I have all arguments for the exchange() to any() in hopes to trigger the condition as often as possible as I can always narrow the conditions at a different time. Am I not mocking my restTemplate correctly? That is my current suspicion as to what is going on. Any advice would help!
Thanks!
Like #JB Nizet pointed out, you are creating a new instance of RestTemplate inside your tested method. This means that the exchange method will be called from the new instance, and not a mock. You could implement it the way you did if the class that contains the method createAppointment had a dependency injection of RestTemplate.
What you want there, is to mock the constructor of the new instance of RestTemplate so that, when a new instance would be created, it will be substituted. Unfortunately, Mockito is not capable of mocking a constructor, so you should use PowerMockito for mocking constructors.
whenNew(RestTemplate.class).withNoArguments().thenReturn(restTemplate);
responseEntity = new ResponseEntity<>(
"some response body",
HttpStatus.OK
);
when(restTemplate.exchange(Mockito.anyString(),
Mockito.<HttpMethod> any(),
Mockito.<HttpEntity<?>> any(),
Mockito.<Class<Object>> any()))
.thenReturn(responseEntity);
I want to make a service with Spring's RestTemplate, in my service side the code is like this :
#PostMapping(path="/savePersonList")
#ResponseBody
public List<Person> generatePersonList(#RequestBody List<Person> person){
return iPersonRestService.generatePersonList(person);
}
In client side if I call the service with this code:
List<Person> p = (List<Person>) restTemplate.postForObject(url, PersonList, List.class);
I can't use the p object as List<Person>, it will become a LinkedHashList.
After some research I find a solution that said I have to call the service with exchange method:
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, personListResult, new ParameterizedTypeReference<List<Person>>() {});
and with this solution the server can't take the object and raise an exception , what's the correct way?
Check if your code is like below. This should work.
//header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//person list
List<Person> personList = new ArrayList<Person>();
Person person = new Person();
person.setName("UserOne");
personList.add(person);
//httpEnitity
HttpEntity<Object> requestEntity = new HttpEntity<Object>(personList,headers);
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Person>>() {});
It may be helpful for you.
List<Integer> officialIds = null;
//add values to officialIds
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<List<Integer>> request = new HttpEntity<List<Integer>>(officialIds,
headers);
ResponseEntity<YourResponseClass[]> responses =
restTemplate.postForEntity("your URL", request , YourResponseClass[].class );
List<YourResponseClass> list = Arrays.asList(responses.getBody());
I had similar challenge, and here are my 2 cents.
My Controller Class with POST Mapping
#PostMapping("/fetch/projects")
public ResponseEntity<List<Project>> getAllProjects(#RequestBody List<UserProject> userProject) {
// Convert List of projectIds to List of Long using Lambda Functions
List<Long> projectIds = userProject.stream().map(UserProject::getProjectId).collect(Collectors.toList());
List<Project> projectList = projectService.getAllProjectsByProjectIds(projectIds);
log.info("<< Fetching Projects based on Project Ids !");
return new ResponseEntity<List<Project>>(projectList, HttpStatus.OK);
}
My Static URL for the above controller
final String projectBaseUri = "http://localhost:6013/api/v1/project/fetch/projects";
My Caller Service
protected List<Project> getProjectsByIds(List<UserProject> userProject) {
String url = projectBaseUri;
log.info("Project URL : " + url);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> requestEntity = new HttpEntity<Object>(userProject,headers);
ResponseEntity<List<Project>> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Project>>() {});
return response.getBody();
}
I want to make a service with Spring's RestTemplate, in my service side the code is like this :
#PostMapping(path="/savePersonList")
#ResponseBody
public List<Person> generatePersonList(#RequestBody List<Person> person){
return iPersonRestService.generatePersonList(person);
}
In client side if I call the service with this code:
List<Person> p = (List<Person>) restTemplate.postForObject(url, PersonList, List.class);
I can't use the p object as List<Person>, it will become a LinkedHashList.
After some research I find a solution that said I have to call the service with exchange method:
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, personListResult, new ParameterizedTypeReference<List<Person>>() {});
and with this solution the server can't take the object and raise an exception , what's the correct way?
Check if your code is like below. This should work.
//header
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
//person list
List<Person> personList = new ArrayList<Person>();
Person person = new Person();
person.setName("UserOne");
personList.add(person);
//httpEnitity
HttpEntity<Object> requestEntity = new HttpEntity<Object>(personList,headers);
ResponseEntity<List<Person>> rateResponse = restTemplate.exchange(url, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Person>>() {});
It may be helpful for you.
List<Integer> officialIds = null;
//add values to officialIds
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
HttpEntity<List<Integer>> request = new HttpEntity<List<Integer>>(officialIds,
headers);
ResponseEntity<YourResponseClass[]> responses =
restTemplate.postForEntity("your URL", request , YourResponseClass[].class );
List<YourResponseClass> list = Arrays.asList(responses.getBody());
I had similar challenge, and here are my 2 cents.
My Controller Class with POST Mapping
#PostMapping("/fetch/projects")
public ResponseEntity<List<Project>> getAllProjects(#RequestBody List<UserProject> userProject) {
// Convert List of projectIds to List of Long using Lambda Functions
List<Long> projectIds = userProject.stream().map(UserProject::getProjectId).collect(Collectors.toList());
List<Project> projectList = projectService.getAllProjectsByProjectIds(projectIds);
log.info("<< Fetching Projects based on Project Ids !");
return new ResponseEntity<List<Project>>(projectList, HttpStatus.OK);
}
My Static URL for the above controller
final String projectBaseUri = "http://localhost:6013/api/v1/project/fetch/projects";
My Caller Service
protected List<Project> getProjectsByIds(List<UserProject> userProject) {
String url = projectBaseUri;
log.info("Project URL : " + url);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Object> requestEntity = new HttpEntity<Object>(userProject,headers);
ResponseEntity<List<Project>> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,new ParameterizedTypeReference<List<Project>>() {});
return response.getBody();
}