Search code examples
springresttemplatespring-test

Spring TestRestTemplate vs RestTemplate


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.


Solution

  • 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