单元测试中的PageableHandlerMethodArgumentResolver不解析排序方向

时间:2016-03-05 11:48:15

标签: junit spring-boot

我有如下所示的控制器和单元测试。控制器返回排序列表。在单元测试中,排序字段正确传递;但是,排序方向没有被解析:

enter image description here

我正在关注这些例子:

Isolated Controller Test can't instantiate Pageable

4. Paging and Sorting

控制器:

@RequestMapping("/telemetry")
public Page<TelemetryMessage> List(Pageable pageable) {
    return telemetryMessageRepository.findAll(pageable);
}

单元测试:

@Before
public void setUp() throws Exception {
    mvc = MockMvcBuilders
            .standaloneSetup(new TelemetryController(telemetryMessageRepository))
            .setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver())
            .setViewResolvers(new ViewResolver() {
                @Override
                public View resolveViewName(String viewName, Locale locale) throws Exception {
                    return new MappingJackson2JsonView();
                }
            })
            .build();
    // etc.
}

@Test
public void testListReturnsDefault20() throws Exception {

    Iterable<TelemetryMessage> expected = telemetryMessageRepository.findAll(new PageRequest(0, 20, Sort.Direction.DESC, "id"));
    String json = mapper.writeValueAsString(expected);

    MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/telemetry")
            .param("sort", "id")
            .param("id.dir", "desc")
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isOk())
            .andReturn();
    String actual = result.getResponse().getContentAsString();

}

1 个答案:

答案 0 :(得分:1)

使用comma分隔PropertyDirection,如下所示:

MvcResult result = mvc.perform(MockMvcRequestBuilders.get("/telemetry")
            .param("sort", "id,desc")
            //.param("id.dir", "desc")