MockMvc 测试 POST 请求

Posted

技术标签:

【中文标题】MockMvc 测试 POST 请求【英文标题】:MockMvc test POST request 【发布时间】:2017-10-28 14:59:54 【问题描述】:

我的 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)

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

提前致谢。

【问题讨论】:

【参考方案1】:

你可以试试:

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

【讨论】:

【参考方案2】:

您应该尝试:

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

最好确保在Movie 类中实现了equalshashCode 方法。

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

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

【讨论】:

【参考方案3】:

假设这是 MovieService 类:

@Component
public class MovieService 

    private static List<Movie> movieList = new ArrayList<>();

    static 
        Movie m1 = new Movie("id1", "title1","2000", "poster1.jpg");
        Movie m2 = new Movie("id2", "title2","2001", "poster2.jpg");
        Movie m3 = new Movie("id3", "title3","2002", "poster3.jpg");
        Movie m4 = new Movie("id4", "title4","2003", "poster4.jpg");
        Movie m5 = new Movie("id5", "title5","2004", "poster5.jpg");

        movieList.add(m1);
        movieList.add(m2);
        movieList.add(m3);
        movieList.add(m4);
        movieList.add(m5);
    

    public Movie saveMovie(Movie movie)
        movieList.add(movie);
        return movie;
    

假设这是 MovieController 类:

@RestController
public class MovieController 

    private final MovieService movieService;

    public MovieController(MovieService movieService) 
        this.movieService = movieService;
    

    @PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity saveMovie(@RequestBody Movie movie)
        movieService.saveMovie(movie);
        return new ResponseEntity<>(movie, HttpStatus.OK);
    

您可以使用 MockMvc 编写如下所示的测试。测试检查响应中的 HttpStatus 是否是预期的:HttpStatus.OK。并检查 saveMovie.saveMovie 是否为 movie6 调用过一次。

@RunWith(SpringRunner.class)
@WebMvcTest(MovieController.class)
public class MovieControllerTest 

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MovieService movieService;

    @Test
    public void saveMovie() throws Exception 
        Movie movie6 = new Movie("id6", "title6", "2006", "poster6.jpg");
        String movie6AsJson = new ObjectMapper().writeValueAsString(movie6);
        String url = "/";

        when(movieService.saveMovie(any(Movie.class))).thenReturn(movie6);

        RequestBuilder requestBuilder = MockMvcRequestBuilders.post(url)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(movie6AsJson);

        MvcResult mvcResult = mockMvc.perform(requestBuilder).andReturn();

        int actualResult = mvcResult.getResponse().getStatus();
        int expectedResult = HttpStatus.OK.value();

        assertEquals("Result not as expected!",expectedResult,actualResult);
        verify(movieService, times(1)).saveMovie(refEq(movie6));
    


【讨论】:

以上是关于MockMvc 测试 POST 请求的主要内容,如果未能解决你的问题,请参考以下文章

MockMvc control层单元测试 参数传递问题

如何正确使用 MockMvc 在 Junit 中测试 post 方法?

MockMvc 测试 OPTIONS 请求

MockMvc control层单元测试 参数传递问题

spring mockMVC测试方法GET

MockMVC的使用