MockMvc测试POST请求

时间:2017-05-28 02:14:46

标签: spring-test mockmvc spring-test-mvc spring-boot-test

我的REST控制器中有以下发布路径:

     @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.domain.Movie@ae372b9
     );
     -> at 

     com.stackroute.ng2boot.controllers.MovieRestControllerTest.
     saveMovie(MovieRestControllerTest.java:129)
     Actual invocation has different arguments:
    com.stackroute.ng2boot.service.MovieService#0 bean.saveMovie(
    com.stackroute.ng2boot.domain.Movie@2098d37d
    );
    -> at     
    com.stackroute.ng2boot.controllers.MovieRestController.
    saveMovie(MovieRestController.java:60)

除了保存和更新,我需要将Movie JSON作为请求主体传递,其他路径正在通过测试。请分享您的宝贵意见。

提前致谢。

2 个答案:

答案 0 :(得分:0)

你可以尝试:

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

答案 1 :(得分:0)

您应该尝试:

verify(movieService).saveMovie(ArgumentMatchers.eq(movie1));

最好在equals类中实现hashCodeMovie方法。

我注意到的另一件小事(但是,与您的问题无关)是您不需要同时使用times(1)verifyNoMoreInteractions(movieService)。默认情况下,Mockito.verify被调用一次。看看它的来源:

public static <T> T verify(T mock) {
    return MOCKITO_CORE.verify(mock, times(1));
}