I am trying to build the REST API JSON Media type using jersey also using jersey test framework for Junit testing.
I have create the GET Method and POST method, while doing JUnit test Get method works fine.
but when try to test the post method through JUnit test method POST Actual Method is not trigger.
Note: when I pass null here target("addresses").request().post(null); I can able to access the actual method. what goes wrong unable to find.
Test Method
#Test
public void testCreateAddressWithoutMandatoryFields() {
TestPojo addressRequest = new TestPojo();
addressRequest.setAddressId(333);
Entity<TestPojo> entiry = Entity.entity(addressRequest, MediaType.APPLICATION_JSON);
Response response = target("addresses").request().post(entiry);
assertEquals("Http Response should be 201 ", Status.CREATED.getStatusCode(), response.getStatus());
}
Actual Method
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response createAddress(#Context TestPojo addressRequest) {
try {
System.out.println("am i here" );
addressRequest.getAddressId();
}catch(Exception e) {
e.printStackTrace();
}
return Response.status(200).entity(null).build();
}
Related
How to mock WebClient.ResponseSpec, expecting response in pojo class list. code as below
public ResponseSpec externalAPICall(RequestBody requestBody) {
//ExternalApi
String url = "http://dev1:8080/external/api";
return client.post().uri(url).contentType(MediaType.APPLICATION_JSON)
.body(Mono.just(requestBody), RequestBody.class).retrieve();
}
tried to mock ResponseSpec with body, but getting NullPointerException
I need to call another rest api endpoint inside the controller class to provide filtered user list as a result. I can't find a way to call one rest api from another rest api.Controller class
This is my controller class method code:
#GET
#Path("/filter")
#Produces(MediaType.APPLICATION_JSON)
public Response filterByName(#QueryParam("page") int page, #QueryParam("first_name") String first_name,
#QueryParam("last_name") String last_name) {
try{
String uri = "https://reqres.in/api/users?page="+page;
//Flux<User1> users = restTemplate.getForObject(uri, User1.class);
Mono<List<User1>> result = users.filter(user-> user.getFirst_name().equals(first_name) && user.getLast_name().equals(last_name)).collectList();
return Response.ok(result).build();
}catch(Exception e) {
e.printStackTrace();
return Response.status(204).build();
}
}
My issue got resolved, I used microprofile rest client to create a proxy and called the endpoint from there. Thanks!
Take a look at the HttpClient class in java.
https://docs.oracle.com/en/java/javase/12/docs/api/java.net.http/java/net/http/HttpClient.html
This is the object we are trying to retrieve:
// Lombok annotated
#Getter
#Setter
#ToString(callSuper = true)
public class GetTransactionsResponse {
public String name;
public List<Transaction> list;
}
We have an object that has metadata and a list of objects
We tried using spring's restTemplate in a method like the following:
public GetTransactionsResponse getTransactions(String token, Request request) {
var requestEntity = RequestEntity
.get(externalApiClient.getTransactionsPath())
.header(HttpHeaders.AUTHORIZATION, token)
.build();
return handleCall(requestEntity, GetTransactionsResponse.class);
}
private <T> T handleCall(RequestEntity<?> requestEntity, Class<T> clazz) {
try {
var result = restTemplate.exchange(requestEntity, clazz).getBody();
log.info("method: handleCall - requestEntity: {} - clazz: {} - result: {}", requestEntity, clazz, result);
return result;
} catch (Exception e) {
throw e
}
}
So we call the rest template but we are receiving null. Without nested data the previous method works but somehow returns null when using nested objects. Are we using rest template wrong?
First verify that your Rest API you created actually works. Test it with posman or ARC (Advanced Rest Client) - a plugin for chrome and see that you get the desired result. If it works, then you can send request to your API from any Http Client including Rest Template. If your API works but calling it from Rest Template doesn't then you will know that the problem is on your client side and you can try and figure out why. But first verify that your Rest API actually works and not returning null
I don't understand the point of this method and can't find any info about it. What is the reason of using it, especially for void methods like in example below? I've tried deleting it in my tests and seems like everything is the same.
Test
#Test
public void deletePatientById_success() throws Exception {
Mockito.when(patientRecordRepository.findById(RECORD_2.getPatientId())).thenReturn(Optional.of(RECORD_2));
mockMvc.perform(MockMvcRequestBuilders
.delete("/patient/2")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
Controller to be tested
#DeleteMapping(value = "{patientId}")
public void deletePatientById(#PathVariable(value = "patientId") Long patientId) throws NotFoundException {
if (patientRecordRepository.findById(patientId).isEmpty()) {
throw new NotFoundException("Patient with ID " + patientId + " does not exist.");
}
patientRecordRepository.deleteById(patientId);
}
The contentType method does not belong to the mockMvc class but to the MockHttpServletRequestBuilder class and it sets the 'Content-Type' header of the request to a specific type (in this case you inform the endpoint that the request body format of your request is JSON).
This basically sets the Content-Type header of the request (in your case JSON).
Check for additional information in https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/request/MockHttpServletRequestBuilder.html#contentType-org.springframework.http.MediaType-
I created different methods for verify if there is empty fields in SOAP and REST services. For Soap i use something like this:
if (fornecedor.isEmpty()) {
throw new BadRequestException(error + " fornecedor");
}
For REST i made this:
if (fornecedor.isEmpty()) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, ERROR + " fornecedor");
}
It means that I have #Context HttpServletResponse response as parameter in Rest and nothing on SOAP because it is an exception. There is other way to verify empty fields using same method for SOAP and REST?
Jersey allows you to map custom exceptions to responses.
The relevant documentation is here:
https://jersey.java.net/documentation/latest/representations.html#d0e5199
Example mapping:
#Provider
public class BadRequestExceptionMapper implements ExceptionMapper<BadRequestException> {
public Response toResponse(BadRequestException ex) {
return Response.status(404).
entity(ex.getMessage()).
type("text/plain").
build();
}
}