2017-04-07 23 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(); 
} 

私はモック残り、簡単の要求このよう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()); 
} 

をしかし、それは仕事をdosn't。ユニットテスト中に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()); 
} 

応答の出力は正しいです!

関連する問題