2017-02-06 7 views
1

私は非同期サービスを呼び出すコントローラをテストする必要があります。MockMVCは非同期サービスへのポストテストを実行します

コントローラコード

@RequestMapping(value = "/path", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE) 
@ResponseBody 
public ResponseEntity<Result> massiveImport(HttpServletRequest request) { 
    try { 
     service.asyncMethod(request); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return new ResponseEntity<>(new Result(e.getMessage()), HttpStatus.BAD_REQUEST); 
    } 

    return new ResponseEntity<>(new Result(saveContact.toString()), HttpStatus.OK); 
} 

サービスコード

@Async 
public Future<Integer> asyncMethod(HttpServletRequest request) throws IllegalFieldValueException, Exception { 
    ... 
    return new AsyncResult<>(value); 
} 

テストコード

MvcResult result = getMvc().perform(MockMvcRequestBuilders.fileUpload("/path/") 
          .header("X-Auth-Token", accessToken) 
          .accept(MediaType.APPLICATION_JSON)) 
          .andDo(print()) 
          .andReturn(); 

テストがOKです。しかし、私は、非同期サービスを完了するために、テストを閉じる前に待つでしょう。

これを行う方法はありますか?

答えて

1

非同期実行が完了するのを待つだけの場合は、MvcResultを参照してください。あなたはgetAsyncResult()でそれを待つことができます。

現在のコードでは、アサーションなしでリクエストを実行しているだけです。したがって、テストは完了していません。完全なテストのためには、以下の2つのステップが必要です。

最初の要求を実行します。

MvcResult mvcResult = getMvc().perform(fileUpload("/path/") 
           .header("X-Auth-Token", accessToken) 
           .accept(MediaType.APPLICATION_JSON)) 
           .andExpect(request().asyncStarted()) 
           .andReturn(); 

その後asyncDispatchを経由して非同期派遣を開始し、アサーションを実行:

getMvc().perform(asyncDispatch(mvcResult)) 
     .andExpect(status().isOk()) 
     .andExpect(content().contentType(...)) 
     .andExpect(content().string(...)); 
関連する問題