Mocktesting RestTemplate using Mockito in Spring boot latest version - spring

I am using 1.3.3.RELEASE version of Spring Boot.
I am trying to unit test my service which uses RestTemplate to call a url for fetching html page.
This is the code
Mockito.when(restTemplate.exchange(
Mockito.anyString(),
Mockito.any(HttpMethod.class),
Mockito.any(HttpEntity.class),
Mockito.any(Class.class)))
.thenReturn(new ResponseEntity<String>("",
new HttpHeaders(), HttpStatus.OK));
But thenReturn part is having issues. What could be the right construction of ResponseEntity for getting an html page.
Appreciate any help.
Thanks

you need to mock out responseEntity
so:
ResponseEntity<String> mockResponse = mock(ResponseEntity.class);
when(mockResponse.getStatusCode()).thenReturn(HttpStatus.OK);
then like you did before:
when(mockRestTemplate.exchange(anyString(), anyObject(), anyObject(), eq(String.class)))
.thenReturn(mockResponse);

Related

How to migrate this mutlipart file upload to Spring Boot 2.4?

With Spring Boot 2.3 I was using the following Kotlin code
val mvcResultImage = this.mockMvc!!.perform(MockMvcRequestBuilders.multipart("/somepath)
.file("files[]", imageFile.getBytes())
.characterEncoding("UTF-8"))
.andReturn()
in an integration test for a controller with a function
#PostMapping(path = ["/somepath"],
consumes = [MediaType.MULTIPART_FORM_DATA_VALUE],
produces = [MediaType.APPLICATION_JSON_VALUE])
#ResponseBody
fun createFromBytes(#RequestParam("files[]") file: MultipartFile): ResponseEntity<Any> {
...
}
In 2.3 I was able to handle the request in the controller function whereas in 2.4 the controller function raises a org.springframework.web.multipart.support.MissingServletRequestPartException with the message Required request part 'files[]' is not present and causes HTTP response code 400.
I don't find anything in the migration guide and list of handled issues for this version change.
A rename to file in both controller and request doesn't help, I don't remember why I added [] in the code working with 2.3, but I think it was necessary to make it work.
I'm using Spring Boot through the maven parent mechanism with spring-boot-starter-parent:2.4.1.
This is a known issues in Spring Boot coming from Spring. It's fixed in Spring Boot 2.4.2. The linked issue contains a successfully tested workaround in case you're stuck with 2.4.1: Create MockMultipartFile with MockMultipartFile( String name, #Nullable String originalFilename, #Nullable String contentType, #Nullable byte[] content) (specification of originalFilename matters).

How do I make spring boot RestTemplate client metrics not create a new tag for query parameters

I've got a spring boot application that is defining a RestTemplate bean as follows:
#Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
Also, pulling in spring-boot-starter-actuator and io.micrometer:micrometer-registry-prometheus.
When I use the injected RestTemplate as follows:
#Autowired
private RestTemplate restTemplate;
private String uriTemplate = "http://my.domain.com/bookstore-api/books";
public List<Book> getBooksByAuthor(String author) {
// create URI for "http://my.domain.com/bookstore-api/books?author={authorId}"
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder
.fromUriString(uriTemplate)
.queryParam("author", author);
// make the GET
ResponseEntity<Book[]> responseEntity = restTemplate.getForEntity(uriComponentsBuilder.toUriString(),Book[].class);
// rest ommitted for brevity
}
When getBooksByAuthor("Tolkien") is called, we can then hit /metrics/prometheus and see the following:
http_client_requests_seconds_count{clientName="my.domain.com",method="GET",status="200",uri="/bookstore-api/books?author=Tolkien",} 2.0
http_client_requests_seconds_sum{clientName="my.domain.com",method="GET",status="200",uri="/bookstore-api/books?author=Tolkien",} 0.253227898
This would be fine, except that there are lots of authors out there, and eventually I will get the "too many tags" exception.
I would prefer to have the following (similar to how path variables get templated):
http_client_requests_seconds_count{clientName="my.domain.com",method="GET",status="200",uri="/bookstore-api/books?author={author}",} 2.0
http_client_requests_seconds_sum{clientName="my.domain.com",method="GET",status="200",uri="/bookstore-api/books?author={author}",} 0.253227898
Is this possible to achieve by modifying the way I use UriComponentsBuilder? The closest thing I've found is to define my own RestTemplateExchangeTagsProvider, and override the default to do some crazy regex replacement.
Just fixed same issue in SpringBoot 2.4.5 using:
responseEntity = restTemplate.exchange(
config.getDataUrl(),
HttpMethod.GET,
httpEntity,
new ParameterizedTypeReference<String>() {},
rowId);
where getDataUrl resolves to:
https://data-service-dev.apps.cloud.net/api/hbase/getData?rowId={rowId}
metrics:
http_client_requests_seconds_count{clientName="data-service-dev.apps.cloud.net",method="GET",outcome="SUCCESS",status="200",uri="/api/hbase/getData?rowId={rowId}",} 1.0
...
I have had a same problem. Maybe this information will help you.
In my case restTemplate.setUriTemplateHandler(handler) had overwritten annonymous
MetricsClientHttpRequestInterceptor#createUriTemplateHandler.
And the original url templates had not been stored into memory for prometheus.
DefaultUriBuilderFactory builderFactory = new DefaultUriBuilderFactory();
builderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE);
customizer.customize(restTemplate);
restTemplate.setUriTemplateHandler(handler);
So,
I changed order of the commands:
restTemplate.setUriTemplateHandler(handler);
customizer.customize(restTemplate);
Please check that there are no setting commands for restTemplate after MetricsClientHttpRequestInterceptor.customize(restTemplate).

spring deferred result response in weblogic

I have implemented DeferredResult in spring MVC. It returns the right response in Tomcat8 but when I deployed into weblogic 12.1.3 gives me 404 error. I tried to debug to find out what is going on then at some point handler is looking for view in web-inf directory. I am confused here.
Could you please help me to understand?
I am using Spring
Java 7
Spring 4.2.0.RELEASE
Spring OAuth2
Weblogic 12.1.3
#RequestMapping(value = "/file/{id}")
#ResponseBody
public DeferredResult<ResponseEntity<Resource>> file(#PathVariable String id) {
DeferredResult<ResponseEntity<Resource>> result = new DeferredResult<>();
try {
final ImageObject image = null;
final Resource fileResource = new FileSystemResource(image.getImagePath().replace("E:", "C:"));
final HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(fileResource.contentLength());
result.setResult(new ResponseEntity<>(fileResource, headers, HttpStatus.OK));
} catch (Exception e) {
}
return result;
}
Thanks in advance.
In my case Spring wrongly concatenated a #RequestMapping path of #RestController and #RequestMapping path of a method. #RequestMapping path of #RestController was duplicated in a resulting URI in Spring logs.
The only workaround I've found is to create #RestControllers for each required DeferredResult method without specifying a #RequestMapping path in the methods.
WebLogic 12.2.1.3.0, Spring 4.3.23.

406 error while mocking File Download REST API using MockMVC

I am implementing a REST API using Spring framework, which returns
return new ResponseEntity<>(new InputStreamResource(myInputStream),
responseHeaders, HttpStatus.OK);
REST API is declared as:
#RequestMapping(value = "/download", method = RequestMethod.GET,
produces = { MediaType.APPLICATION_OCTET_STREAM_VALUE })
While writing unit test for this API, I am using MockMVC like below:
final MappingJackson2HttpMessageConverter messageConverter =
new MappingJackson2HttpMessageConverter();
messageConverter.setObjectMapper(new ObjectMapper());
messageConverter.getObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
this.mockMvc =
MockMvcBuilders.standaloneSetup(myController)
.setMessageConverters(messageConverter)
.apply(new RestDocumentationConfigurer()
.withScheme("https").withHost("localhost")
.withPort(443)).build();
And my Test case looks like this:
mockMvc.perform(
org.springframework.test.web.servlet.request.MockMvcRequestBuilders
.get(restUri))
.andExpect(
org.springframework.test.web.servlet.result.MockMvcResultMatchers
.status().isOk())
.andDo(document("myApi")).andReturn();
But I am getting status as error 406.
java.lang.AssertionError: Status expected:<200> but was:<406>
at org.springframework.test.util.AssertionErrors.fail
What I am missing here?
Any help would be much appreciated.
You inject instance of MappingJackson2HttpMessageConverter to MockMvcBuilders which can't deal with converting classes inheriting from Resource. All you need to do is add ResourceHttpMessageConverter to your test specification:
MockMvcBuilders.standaloneSetup(myController)
.setMessageConverters(messageConverter, new ResourceHttpMessageConverter())
Status code 406 means "Not Acceptable", which indicates that the server is missing a header specifying an accepted content type. You'll need to include that in your mockMvc call.

Make Rest Client using Spring Rest Template

Here is my spring controller code..
#RequestMapping(value= "/save_item",
method = RequestMethod.POST,produces="application/json")
public #ResponseBody ModelMap saveItem(ModelMap model,
#RequestParam("id") String itemId,
#RequestParam("name") String itemName) {
model.addAttribute("itemId",itemId);
return model;
}
How can i make a rest client using spring rest tempalte?.
I need to send two parameters from my rest client(id,name).
Anyone Please help me.
Thanks.
You can create a RestTemplate object and execute as this
ResponseEntity<List<City>> result = restTemplate.exchange(
new StringBuilder(URL).append(city).toString(),
HttpMethod.GET, null, responseType);
In this project you can find a maven project with spring-boot and sptring-web that uses this restTemplate snippet and jackson for the json response
https://github.com/voliveirajr/dev-test

Resources