我正在尝试在使用HttpClient
版本4.5
的类上编写测试。我写的测试真的很慢,所以我试图找出问题所在。我可以编写一个测试来证明我的问题:
public class RequeteurRESTTest extends LocalServerTestBase {
private String startServer(String urlSuffix, HttpRequestHandler handler) throws Exception{
this.serverBootstrap.registerHandler(urlSuffix, handler);
HttpHost target = start();
String serverUrl = "http://localhost:" + target.getPort();
return serverUrl;
}
@Test
public void testCase() throws Exception{
String baseURL = startServer("/api", new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException {
response.setStatusCode(HttpStatus.SC_OK);
}
});
HttpClient httpClient;
httpClient = HttpClients.custom().build();
HttpGet method = new HttpGet(baseURL + "/api");
HttpResponse response = httpClient.execute(method);
}
}
我的问题是该指令:
httpClient.execute(method)
需要10秒才能执行。这很慢,但是我不知道为什么这么慢。我的测试有没有做错任何东西,或者忘记了什么?
最佳答案
如果查看LocalServerTestBase类的源代码,则可以看到以下方法:
@After
public void shutDown() throws Exception {
if(this.httpclient != null) {
this.httpclient.close();
}
if(this.server != null) {
this.server.shutdown(10L, TimeUnit.SECONDS);
}
}
通过在您自己的测试用例中覆盖它,可以将超时设置为0秒。这样可以消除执行过程中出现的延迟。
示例实现:
public class MyClassTest extends LocalServerTestBase{
HttpHost httpHost;
@Before
public void setUp() throws Exception {
super.setUp();
this.serverBootstrap.registerHandler("/*", new HttpRequestHandler() {
@Override
public void handle(HttpRequest request, HttpResponse response, HttpContext context)
throws HttpException, IOException {
System.out.println(request.getRequestLine().getMethod());
response.setStatusCode(HttpStatus.SC_OK);
}
});
httpHost = start();
}
@Test
public void myMethodTest() throws Exception {
//Create an instance and give the server url it should call
MyClass instance = new MyClass(httpHost.toURI());
//Test method that calls the server
instance.myMethod();
}
@After @Override
public void shutDown() throws Exception {
if(this.httpclient != null) {
this.httpclient.close();
}
if(this.server != null) {
this.server.shutdown(0L, TimeUnit.SECONDS);
}
}
}