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);
}
Related
I have an abstract class in which I have a method called getInfo that uses restTemplate.exchange. I want to test method directly using Mockito without creating another concrete class to test this method. However, I am getting the null pointer exception when trying to do so.
When I used the same code to test the same rest client code in a concrete class, it works fine.
Below is the abstract class:
public abstract class classToBeTested{
#Autowired
private RestTemplate restTemplate;
protected Response methodToBeTested(){
String url = "https://example.com";
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<ClaimsResponse> response = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class);
return response;
}
}
#RunWith(MockitoJUnitRunner.class)
public class Test{
#Mock
private RestTemplate restTemplate;
#Test
public void testMethod(){
String url = "https://example.com";
classToBeTested service = Mockito.mock(classToBeTested.class, Mockito.CALLS_REAL_METHODS);
Response res = new Response();
HttpHeaders headers = new HttpHeaders();
HttpEntity<String> entity = new HttpEntity<>(headers);
ResponseEntity<Response> response = new ResponseEntity<>(res, HttpStatus.OK);
Mockito.when(restTemplate.exchange(url, HttpMethod.GET, entity, Response.class)).thenReturn(response);
Response result = service.methodToBeTested();
Assert.assertEquals("should be equal", res, result);
}
}
This test should pass but I am getting null pointer exception on the line below:
ResponseEntity<ClaimsResponse> response = restTemplate.exchange(url, HttpMethod.GET, entity, Response.class)
I am trying to learn RestTemplate and for that made two test spring-boot applications, client and server. Tried some examples on google before asking here, and sorry for the duplicate post if I missed it.
#Slf4j
#RestController
public class ServerController {
#PostMapping("/post")
#ResponseBody
public Resource post(#RequestBody Map<String, String> body,
#RequestParam(name = "path", defaultValue = "NAN") String path) {
if (!body.get("key").equalsIgnoreCase("valid")){
return Resource.builder().ip("'0.0.0.0").scope("KEY NOT VALID").serial(0).build();
}
switch (path) {
case "work":
return Resource.builder().ip("115.212.11.22").scope("home").serial(123).build();
case "home":
return Resource.builder().ip("115.212.11.22").scope("home").serial(456).build();
default:
return Resource.builder().ip("127.0.01").scope("local").serial(789).build();
}
}
}
And here is my ClientController
#Slf4j
#RestController
public class ClientController {
#GetMapping("/get")
public Resource get() {
String url = "http://localhost:8085/post";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setAccept(Arrays.asList(MediaType.MULTIPART_FORM_DATA));
httpHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("key", "valid");
HttpEntity<MultiValueMap<String, String>> entity = new HttpEntity<>(body, httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<Resource> response = restTemplate.exchange(url, HttpMethod.POST, entity, Resource.class, Collections.singletonMap("path", "home"));
return response.getBody();
}
}
In ClientController I am trying to mimic what I did in Postman but without luck.
Postman PrintScreen
What am I doing wrong? Thank you!
Managed to figure it out. Had to refactor like this
#GetMapping("/get")
public Resource get(){
String url = "http://localhost:8085/post";
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("path", "home");
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
HttpEntity<Map<String, String>> request = new HttpEntity<Map<String, String>>(Collections.singletonMap("key", "valid"), httpHeaders);
Resource resource = restTemplate.postForObject(builder.toUriString(), request, Resource.class);
return resource;
}
Can some one tell me how to send a POST request with raw data parameters as in the picture below
i have tried the following code but its not working
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JsonObject properties = new JsonObject();
MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
try {
properties.addProperty("app_id", appId);
properties.addProperty("identity","TestAPI");
properties.addProperty("event", "TestCompleted");
properties.addProperty("testType", t.getTestType());
properties.addProperty("testName",t.getTestName());
properties.addProperty("chapter","");
properties.addProperty("module","");
properties.addProperty("pattern",t.getTestPattern());
HttpEntity<String> request = new HttpEntity<>(
properties.toString(), headers);
// params.add("properties", properties.toString());
restTemplate.postForObject(url, request, String.class);
can someone help?
Try this :
#RestController
public class SampleController {
#RequestMapping("/req")
public String performReqest(){
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
JsonObject properties = new JsonObject();
properties.addProperty("no", "123");
properties.addProperty("name", "stackoverflow");
HttpEntity<String> request = new HttpEntity<>(properties.toString(), headers);
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.postForObject("http://localhost:4040/student", request, String.class);
return "Response from Server is : "+response;
}
#RequestMapping("/student")
public String consumeStudent(#RequestBody Student student){
System.out.println(student);
return "Hello.."+student.name;
}
}
class Student{
public int no;
public String name;
public Map<String,String> properties;
}
Don't forgot to move Student class and change all field to private with require getters and setters.
Above code is only for demo purpose.
Please try with this:
ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
Did u tried using postmaster and checked the output first. If its working then you can go for post or exchange method. exchange returns and post dont.
try this:
URI uri = new URI("something");
Map<String, Object> params = new HashMap<>();
params.put("app_id", "something");
params.put("identity", something);
HttpEntity<Map<String, String>> request = new HttpEntity(params , headers);
ResponseEntity<String> response = restTemplate.postForEntity(uri, request, String.class);
I have one rest service with following implementation -
#RequestMapping(method = RequestMethod.GET, consumes = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
#JsonSerialize
public ResponseEntity<String> handleData(HttpMethod method, HttpServletRequest httpRequest)
throws URISyntaxException, IOException {
BackendRequest request = new BackendRequest();
request.setHttpRequest(httpRequest);
request.setMethod(method);
BackendResponse backendResponse = service.getresponse(request);
ResponseEntity<String> response = backendResponse.getResponse();
return new ResponseEntity<String>(response.getBody(), response.getHeaders(), response.getStatusCode());
// return response;
}
I am getting all the headers and response status correctly but I am not getting the json response. What is wrong here?
I am trying to do following -
https://stackoverflow.com/a/23736527/2197994
Somewhere deep inside the nested calls, I am getting the response from some other backend using spring rest template.
public BackendResponse callBackend(BackendRequest request) throws URISyntaxException, IOException {
String body = null;
ResponseEntity<String> responseEntity = null;
URI uri = new URI("http", null, "localhost", 8080, request.getRequestURL(), request.getQueryString(), null);
MultiValueMap<String, String> requestHeaders = getHeadersInfo(request.getHttpRequest());
if (HttpMethod.POST.equals(request.getMethod())) {
body = request.getHttpRequest().getReader().lines().collect(Collectors.joining(System.lineSeparator()));
responseEntity = restTemplate.exchange(uri, request.getMethod(),
new HttpEntity<String>(body, requestHeaders), String.class);
} else if (HttpMethod.GET.equals(request.getMethod())) {
responseEntity = restTemplate.exchange(uri, request.getMethod(),
new HttpEntity<String>(body, requestHeaders), String.class);
} else {
LOG.warn("Method:{} not supported yet", request.getMethod());
}
BackendResponse response = new BackendResponse();
response.setResponse(responseEntity);
return response;
}
BackendResponse backendResponse = service.getresponse(request) could be the problem. Could you post the content of the method ?
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();
}