是否有一种模拟易于休息的异步HTTP请求的正式方法?
示例代码:
@GET
@Path("test")
public void test(@Suspended final AsyncResponse response) {
Thread t = new Thread() {
@Override
public void run()
{
try {
Response jaxrs = Response.ok("basic").type(MediaType.APPLICATION_JSON).build();
response.resume(jaxrs);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
t.start();
}
我以这种方式拒绝模拟休息 - 容易的请求:
@Test
public void test() throws Exception {
/**
* mock
*/
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(action);
MockHttpRequest request = MockHttpRequest.get("/hello/test");
request.addFormHeader("X-FORWARDED-FOR", "122.122.122.122");
MockHttpResponse response = new MockHttpResponse();
/**
* call
*/
dispatcher.invoke(request, response);
/**
* verify
*/
System.out.println("receive content:"+response.getContentAsString());
}
但是它没有用。我在单元测试期间遇到了BadRequestException。
模拟易于休息的异步HTTP请求的正确方法是什么?
答案 0 :(得分:1)
By reading rest-easy's source code, I finally find a way to work around with asynchronous HTTP request :
@Test
public void test() throws Exception {
/**
* mock
*/
Dispatcher dispatcher = MockDispatcherFactory.createDispatcher();
dispatcher.getRegistry().addSingletonResource(action);
MockHttpRequest request = MockHttpRequest.get("/hello/test");
request.addFormHeader("X-FORWARDED-FOR", "122.122.122.122");
MockHttpResponse response = new MockHttpResponse();
// Add following two lines !!!
SynchronousExecutionContext synchronousExecutionContext = new SynchronousExecutionContext((SynchronousDispatcher)dispatcher, request, response );
request.setAsynchronousContext(synchronousExecutionContext);
/**
* call
*/
dispatcher.invoke(request, response);
/**
* verify
*/
System.out.println("receive content:"+response.getContentAsString());
}
The output of response is correct !!!