Skip to content

Spring Boot Error @Autowired RestTemplateBuilder with junit

Trying to @Autowired a RestTemplate in Spring Boot 2.1.4 using RestTemplateBuilder. When i run junit tests i get an error when trying to autowired RestTemplate.

I saw here: How to autowire RestTemplate using annotations It seems that RestTemplateBuilder is better so i would like to use that.

This is the configuration file :

public class Beans {
    public RestTemplate restTemplate(RestTemplateBuilder builder) {

This is the test class:

@ContextConfiguration(classes = Beans.class)
public class AppTest extends TestCase {
    private RestTemplate restTemplate;

The error is :



Parameter 0 of method restTemplate in beanDeclerations.Beans required a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' that could not be found.

The injection point has the following annotations:
    - @org.springframework.beans.factory.annotation.Autowired(required=true)


Consider defining a bean of type 'org.springframework.boot.web.client.RestTemplateBuilder' in your configuration.

I edited out other autowired that work. What am i missing here? After searching the web i found out that spring auto wired RestTemplateBuilder, why isn’t doing so here?

EDIT: I ended up using @RestClientTest() and had to move RestTemplateBuilder Bean to the main class for now, I’ll move it later to a different place. Thanks for the help.



The RestTemplateBuilder should be available through an autocofiguration (see: I think this config is missing because of your @ContextConfiguration. You have some possibilities. Try to add the AutoConfig for the RestTemplateBuilder to your ContextConfiguration. Second one is to make a TestConfiguration and create your own RestTemplateBuilder or directly a RestTemplate. The third one is don’t inject the RestTemplate – build it by hand in your test. You can also remove the @ContextConfiguration-Annotation but this will result in a test which loads every config you have defined in your project.

There’s also a RestTestTemplate ( which is designed for tests.

@ContextConfiguration(classes = {TestConfig.class, RestTemplateAutoConfiguration.class})
public class SandboxApplicationTests {

    RestTemplate restTemplate;

    public void contextLoads() {


The snippet above works for me. Without the RestTemplateAutoConfiguration in the ContextConfiguration the RestTemplate can’t be created because of the missing RestTemplateBuilder-Bean

User contributions licensed under: CC BY-SA
4 People found this is helpful