我已经为RestTemplate(RestTemplateInterceptor.class)实现了一个拦截器:
@Autowired
private RestConfigurations configurations;
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.additionalInterceptors((ClientHttpRequestInterceptor) (httpRequest, bytes, clientHttpRequestExecution) -> {
HttpHeaders headers = httpRequest.getHeaders();
headers.add("X-API-KEY", configurations.getApiKey());
return clientHttpRequestExecution.execute(httpRequest,bytes);
}).build();
}
现在我想测试一下。:) 一次尝试看起来像这样:
@ExtendWith(SpringExtension.class)
@RestClientTest({RestTemplateInterceptor.class, RestConfigurations.class})
@AutoConfigureMockMvc
@SpringBootTest
class MyTestClass {
public static final String URL = "http://testMe.com/";
@Autowired
MockRestServiceServer mockServer;
@Autowired
RestTemplateBuilder restTemplateBuilder;
@Test
@DisplayName("Should include header X-API-KEY")
void headerShouldContainsXApiKey() throws Exception {
mockServer.expect(requestTo(URL)).andRespond(withSuccess("Hello world", TEXT_PLAIN));
String body = restTemplateBuilder.build().exchange(URL//
, GET, //
null, //
String.class).getBody();
assertThat(body).isEqualTo("Hello world");
mockServer.expect(header("X-API-KEY", ""));
}
但我失败了:
java.lang.AssertionError: 预期没有进一步的请求:HTTP GET http://test.hornbach.de/ 0 个请求已执行。
任何人的提示?谢谢
qq_花开花谢_0
相关分类