相关疑难解决方法(0)

隔离控制器测试无法实例化Pageable

我有一个Spring MVC控制器,它使用Spring-Data的分页支持:

@Controller
public class ModelController {

    private static final int DEFAULT_PAGE_SIZE = 50;

    @RequestMapping(value = "/models", method = RequestMethod.GET)
    public Page<Model> showModels(@PageableDefault(size = DEFAULT_PAGE_SIZE) Pageable pageable, @RequestParam(
            required = false) String modelKey) {

//..
        return models;
    }

}
Run Code Online (Sandbox Code Playgroud)

我想使用漂亮的Spring MVC测试支持测试RequestMapping.为了使这些测试保持快速并与所有其他内容隔离开来,我不想创建完整的ApplicationContext:

public class ModelControllerWebTest {
    private MockMvc mockMvc;

    @Before
    public void setup() {
        ModelController controller = new ModelController();
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    public void reactsOnGetRequest() throws Exception {
        mockMvc.perform(get("/models")).andExpect(status().isOk());
    }

}
Run Code Online (Sandbox Code Playgroud)

这种方法适用于其他控制器,它们不期望使用Pageable,但是有了这个,我得到了一个很好的长Spring堆栈跟踪.它抱怨无法实例化Pageable:

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is …
Run Code Online (Sandbox Code Playgroud)

testing spring-mvc spring-data spring-mvc-test

37
推荐指数
3
解决办法
1万
查看次数

无法实例化Pageable bean

我使用Spring 4.1.6.RELEASE和Spring Data Jpa 1.8.0.RELEASE.我有org.springframework.data.domain.Pageable bean创建的问题.它在我的控制器中使用:

@Controller
public class ItemsController {

    @Autowired
    ProductService itemsService;

    @RequestMapping(value = "/openItemsPage")
    public String openItemsPage() {
        return "items";
    }

    @RequestMapping(value = "/getItems", method = RequestMethod.GET)
    @ResponseBody
    public Item[] getItems(Pageable pageable) {

        return itemsService.getItems(pageable);
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,我在我的应用程序上下文中有下一个xml配置:

<context:component-scan base-package="com.mobox.controller" />

<mvc:annotation-driven>
    <mvc:argument-resolvers>
        <beans:bean id="sortResolver"
                class="org.springframework.data.web.SortHandlerMethodArgumentResolver" />
        <beans:bean
                class="org.springframework.data.web.PageableHandlerMethodArgumentResolver">
            <beans:constructor-arg ref="sortResolver" />
        </beans:bean>
    </mvc:argument-resolvers>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)

最后,我做了客户的下一次重新计划:

   $.ajax({
        type: "GET",
        url: "getProducts?page=0&size=100",
        .....
Run Code Online (Sandbox Code Playgroud)

在tomcat日志中我看到下一个:

    SEVERE: Servlet.service() for servlet [appServlet] in context with path [/a2delivery-web] threw exception [Request processing …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-data-jpa

17
推荐指数
2
解决办法
1万
查看次数