Quick Guide to @RestClientTest in Spring Boot – Spring Boot中@RestClientTest的快速指南

最后修改: 2016年 7月 23日

1. Introduction


This article is a quick introduction to the @RestClientTest annotation.


The new annotation helps simplify and speed up the testing of REST clients in your Spring applications.


2. REST Client Support in Spring Boot Pre-1.4

2.Spring Boot Pre-1.4中的REST客户端支持

Spring Boot is a handy framework that provides many auto-configured Spring beans with typical settings that allow you to concentrate less on configuration of a Spring application and more on your code and business logic.

Spring Boot是一个方便的框架,它提供了许多具有典型设置的自动配置的Spring Bean,使你可以减少对Spring应用的配置,而更多地关注你的代码和业务逻辑。

But in version 1.3 we don’t get a lot of help when we want to create or test REST services clients. Its support for REST clients is not very deep.


To create a client for a REST API – a RestTemplate instance is typically used. Usually it has to be configured before usage and its configuration may vary, so Spring Boot does not provide any universally configured RestTemplate bean.

要为REST API创建一个客户端,通常要使用RestTemplate实例。通常,在使用前必须对其进行配置,其配置可能会有所不同,因此Spring Boot没有提供任何普遍配置的RestTemplate Bean。

Same goes for testing REST clients. Before Spring Boot 1.4.0, the procedure of testing a Spring REST client was not very different than in any other Spring-based application. You would create a MockRestServiceServer instance, bind it to RestTemplate instance under test and provide it with mock responses to requests, like this:

测试REST客户端也是如此。在Spring Boot 1.4.0之前,测试Spring REST客户端的程序与其他基于Spring的应用程序没有太大区别。你可以创建一个MockRestServiceServer实例,将其与被测的RestTemplate实例绑定,并向其提供模拟的请求响应,就像这样。

RestTemplate restTemplate = new RestTemplate();

MockRestServiceServer mockServer =

// Test code that uses the above RestTemplate ...


You would also have to initialize the Spring container and make sure that only the needed components are loaded into the context, to speed up the context load time (and consequently, the test execution time).


3. New REST Client Features in Spring Boot 1.4+

3.Spring Boot 1.4+中新的REST客户端功能

In Spring Boot 1.4, the team has made a solid effort to simplify and speed up the creation and testing of REST clients.

在Spring Boot 1.4中,团队为简化和加快REST客户端的创建和测试做出了坚实的努力。

So, let’s check out the new features.


3.1. Adding Spring Boot to Your Project

3.1.将Spring Boot添加到您的项目中

First, you’ll need to make sure your project is using Spring Boot 1.4.x or higher:

首先,你需要确保你的项目使用的是Spring Boot 1.4.x或更高版本。

    <relativePath/> <!-- lookup parent from repository -->

Newest release versions can be found here.


3.2. RestTemplateBuilder


Spring Boot brings both the auto-configured RestTemplateBuilder to simplify creating RestTemplates, and the matching @RestClientTest annotation to test the clients built with RestTemplateBuilder. Here’s how you can create a simple REST client with RestTemplateBuilder auto-injected for you:

Spring Boot既带来了自动配置的RestTemplateBuilder,以简化创建RestTemplates,也带来了匹配的@RestClientTest注释,以测试用RestTemplateBuilder构建的客户端。下面是你如何创建一个简单的REST客户端,并为你自动注入RestTemplateBuilder

public class DetailsServiceClient {

    private final RestTemplate restTemplate;

    public DetailsServiceClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder.build();

    public Details getUserDetails(String name) {
        return restTemplate.getForObject("/{name}/details",
          Details.class, name);

Notice that we did not explicitly wire the RestTemplateBuilder instance to a constructor. This is possible thanks to a new Spring feature called implicit constructor injection, which is discussed in this article.


RestTemplateBuilder provides convenience methods for registering message converters, error handlers, URI template handlers, basic authorization and also use any additional customizers that you need.


3.3. @RestClientTest


For testing such a REST client built with RestTemplateBuilder, you may use a SpringRunner-executed test class annotated with @RestClientTest. This annotation disables full auto-configuration and only applies configuration relevant to REST client tests, i.e. Jackson or GSON auto-configuration and @JsonComponent beans, but not regular @Component beans.


@RestClientTest ensures that Jackson and GSON support is auto-configured, and also adds pre-configured RestTemplateBuilder and MockRestServiceServer instances to the context. The bean under test is specified with value or components attribute of the @RestClientTest annotation:


public class DetailsServiceClientTest {

    private DetailsServiceClient client;

    private MockRestServiceServer server;

    private ObjectMapper objectMapper;

    public void setUp() throws Exception {
        String detailsString = 
          objectMapper.writeValueAsString(new Details("John Smith", "john"));
          .andRespond(withSuccess(detailsString, MediaType.APPLICATION_JSON));

    public void whenCallingGetUserDetails_thenClientMakesCorrectCall() 
      throws Exception {

        Details details = this.client.getUserDetails("john");

        assertThat(details.getName()).isEqualTo("John Smith");

Firstly, we need to ensure that this test is run with SpringRunner by adding the @RunWith(SpringRunner.class) annotation.


So, what’s new?


First – the @RestClientTest annotation allows us to specify the exact service under test – in our case it is the DetailsServiceClient class. This service will be loaded into the test context, while everything else is filtered out.


This allows us to autowire the DetailsServiceClient instance inside our test and leave everything else outside, which speeds up the loading of the context.


Second – as the MockRestServiceServer instance is also configured for a @RestClientTest-annotated test (and bound to the DetailsServiceClient instance for us), we can simply inject it and use.

第二 – 由于MockRestServiceServer实例也被配置为@RestClientTest注释的测试(并为我们绑定到DetailsServiceClient实例),我们可以简单地注入它并使用。

Finally – JSON support for @RestClientTest allows us to inject the Jackson’s ObjectMapper instance to prepare the MockRestServiceServer’s mock answer value.


All that is left to do is to execute the call to our service and verify the results.


4. Conclusion


In this article we’ve discussed the new @RestClientTest annotation that allows easy and quick testing of REST clients built with Spring.


The source code for the article is available on GitHub.