spring-bootspring-resttemplate

Springboot 3 resttemplate unit test how to inject


My environment is Spring Boot 3.0.5:

I need to implement Unit Test for a service method login() that use RestTemplate

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = PosteDeliveryClientImpl.class)
public class DeliveryBusinessClientTests {

    @Autowired
    private PosteDeliveryClientImpl posteDeliveryClient;


    public DeliveryBusinessClientTests() {

    }

    @Test
    public void login() {

        var loginResponse = posteDeliveryClient.login();

        assertEquals("Bearer", loginResponse.getToken_type());
    }

The service is define as below:

@Service
public class PosteDeliveryClientImpl implements  PosteDeliveryClient {

    @Autowired
    private RestTemplate restTemplate;

    ...

    @Override
    public LoginResponse login() {
        var loginRequest = new LoginRequest("xxxxxxxxxx",
                                            "xxxxxxxx",
                                            "api://xxxxxxxxxx/.default",
                                            "client_credentials");

        ResponseEntity<LoginResponse> response = restTemplate.postForEntity(ROOT_URI, loginRequest,        LoginResponse.class);
        return response.getBody();
    }

}

When i run test i receive:

Field restTemplate in it.posweb.service.pti.PosteDeliveryClientImpl 
required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.

Action:

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

How to solve injection correctly?

I try add bean on a config class but injection not works:

@Configuration
public class RestTemplateConfig extends RestTemplate {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.build();
    }

    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder();
    }
}

Thanks Daniele

:


Solution

  • Since you "only" @SpringBootTest(classes = PosteDeliveryClientImpl.class) (load selective classes/packages into spring test context), RestTemplate (auto/custom) configuration seems not to get picked up.

    Possible solutions:

    1. Import/re-use your RestTemplate (auto/custom) configuration:

      • via @SpringBootTest#classes
      • in any other possible/reasonable way...

      ((builder!) auto-configuration is (currently) in org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration ;)

    2. Configure a new one:

      • a real one (based on custom/auto configuration)
      • a mock one...