我有一个具有 RestTemplate 依赖项的类
@Service
public class SwiftAPIPushHandler {
private final ObjectMapper objectMapper;
private final RestTemplate restTemplate;
@Value("${app.swift.host}")
private String swiftHost;
@Value("${app.swift.client.secret}")
private String clientSecret;
public SwiftAPIPushHandler(@Autowired RestTemplate restTemplate,
@Autowired ObjectMapper objectMapper) {
this.restTemplate = restTemplate;
this.objectMapper = objectMapper;
}
@ServiceActivator
public Map<String, Object> outboundSwiftPushHandler(Map<String, Object> payload,
@Header("X-UPSTREAM-WEBHOOK-SOURCE") String projectId) throws JsonProcessingException {
// HTTP POST Request from RestTemplate here
}
}
在测试中我希望使用
@RestClientTest
自动配置 RestTemplate
@RestClientTest
@SpringJUnitConfig(classes = {SwiftAPIPushHandler.class})
public class SwiftAPIPushHandlerTest {
@Autowired
SwiftAPIPushHandler apiPushHandler;
@Test
public void testSwiftApiPush(
@Value("classpath:sk-payloads/success-response.json") Resource skPayload) throws IOException {
// blah blah blah
}
}
但是测试失败,无法找到 RestTemplate 错误的自动装配候选者。
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in com.swift.cloud.transformation.engine.SwiftAPIPushHandler required a bean of type 'org.springframework.web.client.RestTemplate' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.
在
@RestClientTest
的文档中您可以阅读:
如果你测试的bean不使用RestTemplateBuilder而是直接注入RestTemplate,你可以添加@AutoConfigureWebClient(registerRestTemplate = true)。
因此,如果您添加到测试类
@AutoConfigureWebClient(registerRestTemplate = true)
,它应该正确注入restTemplate。
@RestClientTest
@AutoConfigureWebClient(registerRestTemplate = true)
@SpringJUnitConfig(classes = {SwiftAPIPushHandler.class})
public class SwiftAPIPushHandlerTest {
另一种方法是在您的服务中注入
RestTemplateBuilder
,在这种情况下,您在测试中不需要 @AutoConfigureWebClient
注释:
@Autowired
public SwiftAPIPushHandler(RestTemplateBuilder restTemplateBuilder, ObjectMapper objectMapper) {
this.restTemplate = restTemplateBuilder.build();
this.objectMapper = objectMapper;
}
您需要使用resttemplate builder配置resttemplate 将其添加到您的项目中
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
Duration duration = Duration.ofMinutes(1);
return builder.setConnectTimeout(duration).setReadTimeout(duration).build();
}
}