What is the difference between RestTemplate
and its test version? When we do exception handling through @ControllerAdvice
, RestTemplate is throwing the exception, but for same flow test version is returning json containing exception details.
So, I wanted to see the summary of differences between them.
TestRestTemplate is not an extension of RestTemplate, but rather an alternative that simplifies integration testing and facilitates authentication during tests. It helps in customization of Apache HTTP client, but also it can be used as a wrapper of RestTemplate.
When we use the RestTemplate to call the RESTful service, it creates duplication of code that talks to RESTful services. When we define Feign, we need only to define a proxy and define a single method into it. Feign helps us to simplify client code to talk to the RESTful web services.
Compared to RestTemplate , WebClient has a more functional feel and is fully reactive. Since Spring 5.0, RestTemplate is deprecated. It will probably stay for some more time but will not have major new features added going forward in future releases. So it's not advised to use RestTemplate in new code.
The restTemplate
give you more possibility, testRestTemplate
is only a wrapper of restTemplate
which offers you convenient approach, like you said, it doesn't throw exception, but wrap it with json response, such behavior should be implemented by yourself in the real application, but you may not care in the test.
here is the javadoc from testRestTemplate
/**
* Convenient subclass of {@link RestTemplate} that is suitable for integration tests.
* They are fault tolerant, and optionally can carry Basic authentication headers. If
* Apache Http Client 4.3.2 or better is available (recommended) it will be used as the
* client, and by default configured to ignore cookies and redirects.
*
* @author Dave Syer
* @author Phillip Webb
*/
The similar pattern can be found by ReflectionTestUtils
and ReflectionUtils
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With