【发布时间】:2018-09-02 16:16:16
【问题描述】:
为设置安全 cookie 的 REST 端点编写 JUnit Integrtaion 测试无法通过 ResourceAccessException 错误。
要求是发出https://localhost:8443 请求。
尝试使用 customRestTemplate
得到以下异常。
org.springframework.web.client.ResourceAccessException:对“https://localhost:8443/dcs”的 GET 请求出现 I/O 错误:连接到 localhost:8443 [localhost/127.0.0.1, localhost/0:0:0: 0:0:0:0:1]失败:连接被拒绝:连接;嵌套异常是 org.apache.http.conn.HttpHostConnectException
下面是代码。
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class DcsServiceTests {
@Autowired
RestTemplateBuilder restTemplateBuilder;
@Autowired
private TestRestTemplate testRestTemplate;
@Test
public void testGet_ImageResponse() throws Exception {
//Arrange
//Act
ResponseEntity<byte[]> response = testRestTemplate.getForEntity(url, byte[].class);
//Assert
//Response Status
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
//Response has cookie
assertThat(response.getHeaders().containsKey("Set-Cookie")).isTrue();
}
@PostConstruct
public void initialize() {
// Lambda expression not working, TBD - Java version used.
//TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
final TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(java.security.cert.X509Certificate[] arg0, String arg1)
throws CertificateException {
return true;
}
};
HttpComponentsClientHttpRequestFactory requestFactory =
new HttpComponentsClientHttpRequestFactory();
try {
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
.loadTrustMaterial(null, acceptingTrustStrategy)
.build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
CloseableHttpClient httpClient = HttpClients.custom()
.setSSLSocketFactory(csf)
.build();
requestFactory.setHttpClient(httpClient);
}
catch (Exception e) {
System.out.println("Exception occured creating Request Factory");
}
RestTemplate customTemplate = restTemplateBuilder
.requestFactory(requestFactory)
.rootUri("https://localhost:8443")
.build();
this.testRestTemplate = new TestRestTemplate(
customTemplate,
null,
null, // Not using basic auth
TestRestTemplate.HttpClientOption.ENABLE_COOKIES); // Cookie support
}
}
【问题讨论】:
标签: spring-boot junit