Unit testing 如何轻松模拟休息';什么是异步HTTP请求?
有没有一种正式的方法来模拟rest轻松异步HTTP请求 示例代码:Unit testing 如何轻松模拟休息';什么是异步HTTP请求?,unit-testing,mocking,resteasy,Unit Testing,Mocking,Resteasy,有没有一种正式的方法来模拟rest轻松异步HTTP请求 示例代码: @GET @Path("test") public void test(@Suspended final AsyncResponse response) { Thread t = new Thread() { @Override public void run() { try { Response jaxrs =
@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();
}
我经常这样模仿rest easy的请求:
@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());
}
但它不起作用。在单元测试期间,我遇到了一个异常
模拟rest easy异步HTTP请求的正确方法是什么?通过阅读rest easy的源代码,我终于找到了解决异步HTTP请求的方法:
@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());
}
响应的输出是正确的