2017-04-07 36 views
1

是否有一種官方的方式來模擬一個簡單的異步HTTP請求?如何模擬rest-easy的異步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(); 
} 

我見於Ger.Offen模擬休息,輕鬆的要求是這樣的:

@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請求?

回答

1

通過閱讀休息,容易的源代碼,我終於找到一個方法來解決異步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()); 
} 

響應的輸出是正確的!