首页 > 解决方案 > 可分页实例化在 WebMvcTest 中成功,在运行服务器上失败

问题描述

我有点被这个难住了。我看到的例子和我在网上找到的所有东西都说这个

public ResponseEntity<StandaloneTerminals> getTerminalsBySearchTerm(
        @PathParam("term") String term, @PageableDefault(page = 0, size = 25) Pageable pageRequest) {
    Page<StandaloneTerminal> terminals;
    ...
}

应该管用。在单元测试中运行时

@RunWith(SpringRunner.class)
@WebMvcTest(TerminalController.class)
public class TerminalControllerTest {
...

@Test
public void getAll() throws Exception {
    MvcResult result = this.mockMvc.perform(get("/terminals")).andDo(print())             
            .andExpect(status().is(200))
            .andReturn();
    ...
}

确实如此!

但是,实际上将 Postman 指向该端点会导致

org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.domain.Pageable]: Specified class is an interface

我已经阅读了有关此问题的 Stack Overflow 上的多个问题,并尝试将 @EnableSpringDataWebSupport 添加到新的 WebConfig 类以及在不同时间添加到我的 AppConfig 和 Controller 中,以确保安全。Spring 继续拒绝实例化这个 bean。

编辑:应用程序配置,根据要求:

@SpringBootApplication
@EnableSpringDataWebSupport
public class AppConfig {

    public static void main(String[] args) {
        SpringApplication.run(AppConfig.class, args);
    }
}

标签: javaspringspring-boot

解决方案


我们永远无法弄清楚 Spring 无法实例化这个 bean 的确切原因,但是我们通过使用默认构造函数来实现我们自己的 Pageable 找到了一种非侵入性的解决方法。到目前为止,我们还没有让 Sort 以同样的方式工作。


推荐阅读