我的env是spring-boot 3.0.5:
我需要为使用REST模板的服务方法login()实现Uinit测试
@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());
}
服务定义如下:
@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();
}
当我运行测试时,我收到:
it.posweb.service.pti.PosteDeliveryClientImpl中的字段restTemplate需要类型为“org.springframework.web.client.RestTemplate”的bean,但找不到。
行动:
考虑在配置中定义一个类型为'org.springframework.web.client.RestTemplate'的bean。
如何正确解决注射?
我尝试在配置类上添加bean,但注入不起作用:
@Configuration
public class RestTemplateConfig extends RestTemplate {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder();
}
}
谢谢丹尼尔
:
1条答案
按热度按时间pcww981p1#
由于你“只”
@SpringBootTest(classes = PosteDeliveryClientImpl.class)
(将选择性的类/包加载到spring test上下文中),RestTemplate
(自动/自定义)配置似乎不会被选中。可能的解决办法:
RestTemplate
(自动/自定义)配置:@SpringBootTest#classes
((builder!)auto-configuration is(currently)in
org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration
;)