2017-05-28 128 views
1

我在我的REST控制器以下職位路線:MockMvc測試POST請求

@RequestMapping(value = "", method = RequestMethod.POST, produces = 
"application/json") 
public ResponseEntity saveMovie(@RequestBody Movie movie){ 
    movieService.saveMovie(movie); 
    return new ResponseEntity<Movie>(movie, HttpStatus.OK); 
} 

路由使用服務添加在請求體中的數據存儲通過了電影。 服務方法的簽名是這樣的:

Movie saveMovie(Movie movie); 

我寫了下面的測試,併爲它的輔助方法:

@Test 
    public void saveMovie() throws Exception { 
    Movie movie1 = new Movie(); 
    movie1.setImdbID("imdb1"); 
    movie1.setTitle("Meter"); 
    movie1.setYear("2015"); 
    movie1.setPoster("meter.jpg"); 

    when(movieService.saveMovie(movie1)).thenReturn(movie1); 
    mockMvc.perform(post("/v1/api/movie") 
      .contentType(MediaType.APPLICATION_JSON_UTF8) 
      .content(asJsonString(movie1)) 
      .accept(MediaType.APPLICATION_JSON)) 
      .andExpect(status().isOk())     
      .andExpect(content().contentType 
       (MediaType.APPLICATION_JSON_UTF8_VALUE)); 
      verify(movieService, times(1)).saveMovie(movie1); 
      verifyNoMoreInteractions(movieService); 
} 



public static String asJsonString(final Object obj) { 
    try { 
     final ObjectMapper mapper = new ObjectMapper(); 
     final String jsonContent = mapper.writeValueAsString(obj); 
     System.out.println(jsonContent); 
     return jsonContent; 
    } catch (Exception e) { 
     throw new RuntimeException(e); 
    } 
} 

我收到以下錯誤:

Argument(s) are different! Wanted: 
com.stackroute.ng2boot.service.MovieService#0 bean.saveMovie(
    com.stackroute.ng2boot.[email protected] 
); 
-> at 

com.stackroute.ng2boot.controllers.MovieRestControllerTest. 
saveMovie(MovieRestControllerTest.java:129) 
Actual invocation has different arguments: 
com.stackroute.ng2boot.service.MovieService#0 bean.saveMovie(
[email protected] 
); 
-> at  
com.stackroute.ng2boot.controllers.MovieRestController. 
saveMovie(MovieRestController.java:60) 

除了保存和更新之外,我需要將Movie JSON作爲請求主體傳遞,其他的路由都通過測試。請分享您的寶貴意見。

在此先感謝。

回答

0

你可以嘗試:

import static org.mockito.Matchers.refEq; 
---- 
verify(movieService, times(1)).saveMovie(refEq(movie1));