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
:
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:
Import/re-use your RestTemplate
(auto/custom) configuration:
@SpringBootTest#classes
((builder!) auto-configuration is (currently) in org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
;)
Configure a new one: