我正在测试spring-boot应用程序并希望检查简单的get请求。问题是如果我用我们的开发服务器替换localhost一切正常。 但不是localhost。
这是父测试类:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceStarter.class)
public abstract class AbstractModulIntegrationTest { ... }
问题:
@Test
public void testGetRequest() {
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credentials
= new UsernamePasswordCredentials("user", "pass");
provider.setCredentials(AuthScope.ANY, credentials);
HttpClient httpClient = HttpClientBuilder.create()
.setDefaultCredentialsProvider(provider)
.build();
HttpGet request = new HttpGet("http://localhost:9000/abc/v1/users/001");
HttpResponse response = null;
try {
response = httpClient.execute(request); //HERE IT FAILS
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("RETURN CODE:" + response.getStatusLine().getStatusCode());
}
Stracktrace:
org.apache.http.conn.HttpHostConnectException: Connect to localhost:9000 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:159)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:359)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:381)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:237)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:185)
at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:111)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:56)
...
Caused by: java.net.ConnectException: Connection refused: connect
感谢任何帮助。
答案 0 :(得分:3)
@SpringBootTest
无法启动Web服务器。您可以使用webEnvironment
属性
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceStarter.class, webEnvironment = RANDOM_PORT)
public abstract class AbstractModulIntegrationTest { ... }
您可以按如下方式在测试中注入服务器的实际端口:
@LocalServerPort
private int port;
public void testGetRequest() { ... }
如果要在已定义的端口上启动,可能已将应用程序配置为从端口9000(server.port=9000
)开始。然后你应该这样做:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MyServiceStarter.class, webEnvironment = DEFINED_PORT)
public abstract class AbstractModulIntegrationTest { ... }