Class TestRestTemplate

java.lang.Object
org.springframework.boot.resttestclient.TestRestTemplate

public class TestRestTemplate extends Object
Convenient alternative of RestTemplate that is suitable for integration tests. TestRestTemplate is fault-tolerant. This means that 4xx and 5xx do not result in an exception being thrown and can instead be detected through the response entity and its status code.

A TestRestTemplate can optionally 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.

Note: To prevent injection problems this class intentionally does not extend RestTemplate. If you need access to the underlying RestTemplate use getRestTemplate().

If you are using the @SpringBootTest annotation with an embedded server, a TestRestTemplate can be auto-configured by adding @AutoConfigureTestRestTemplate to your test class. It can then be @Autowired into your test. If you need customizations (for example to adding additional message converters) use a RestTemplateBuilder @Bean.

Since:
4.0.0
Author:
Dave Syer, Phillip Webb, Andy Wilkinson, Kristine Jetzke, Dmytro Nosan, Yanming Zhou
  • Constructor Details

    • TestRestTemplate

      public TestRestTemplate(RestTemplateBuilder restTemplateBuilder)
      Create a new TestRestTemplate instance.
      Parameters:
      restTemplateBuilder - builder used to configure underlying RestTemplate
    • TestRestTemplate

      public TestRestTemplate(TestRestTemplate.HttpClientOption... httpClientOptions)
      Create a new TestRestTemplate instance.
      Parameters:
      httpClientOptions - client options to use if the Apache HTTP Client is used
    • TestRestTemplate

      public TestRestTemplate(@Nullable String username, @Nullable String password, TestRestTemplate.HttpClientOption... httpClientOptions)
      Create a new TestRestTemplate instance with the specified credentials.
      Parameters:
      username - the username to use (or null)
      password - the password (or null)
      httpClientOptions - client options to use if the Apache HTTP Client is used
    • TestRestTemplate

      public TestRestTemplate(RestTemplateBuilder builder, @Nullable String username, @Nullable String password, TestRestTemplate.HttpClientOption... httpClientOptions)
      Create a new TestRestTemplate instance with the specified credentials.
      Parameters:
      builder - builder used to configure underlying RestTemplate
      username - the username to use (or null)
      password - the password (or null)
      httpClientOptions - client options to use if the Apache HTTP Client is used
  • Method Details