【问题标题】:Spring boot testing error: java.lang.IllegalArgumentException: Page must not be nullSpring boot 测试错误:java.lang.IllegalArgumentException: Page must not be null
【发布时间】:2019-02-07 19:44:37
【问题描述】:

我正在尝试测试以下控制器:

@RepositoryRestController
@RequestMapping("movies")
public class MovieController {

    private MovieService movieService;
    private PagedResourcesAssembler<Movie> pagedAssembler;
    private MovieResourceAssembler movieResourceAssembler;

    @Autowired
    public void setMovieService(MovieService movieService) {
        this.movieService = movieService;
    }

    @Autowired
    public void setPagedAssembler(PagedResourcesAssembler<Movie> pagedAssembler) {
        this.pagedAssembler = pagedAssembler;
    }

    @Autowired
    public void setMovieResourceAssembler(MovieResourceAssembler movieResourceAssembler) {
        this.movieResourceAssembler = movieResourceAssembler;
    }

    // Return all movies with pagination
    @GetMapping
    public ResponseEntity<?> getAllMovies(Pageable pageable) {
        Page<Movie> moviePage = this.movieService.getAllMovies(pageable);
        // Remove some unnecessary fields
        //this.movieService.removeUndesirableFieldsFromListing(moviePage);
        return ResponseEntity.ok(this.pagedAssembler.toResource(moviePage, this.movieResourceAssembler));
    }
 }

这是测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class MovieControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private MovieService movieService;

    @Test
    public void getAllMovies_PageableGiven_ShouldReturnMoviesPage() throws Exception {
        List<Movie> movieList = new ArrayList<>();
        movieList.add(new Movie());
        movieList.add(new Movie());
        Page<Movie> moviePage = new PageImpl<>(movieList);
        given(this.movieService.getAllMovies(PageRequest.of(0,2)))
                .willReturn(moviePage);
        this.mockMvc.perform(get("http://localhost:8080/api/movies?page=1"))
                .andExpect(status().isOk());
    }
}

我收到以下错误:

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 java.lang.IllegalArgumentException: Page 不能为空!

【问题讨论】:

  • 你能发布完整的 stafktrace 吗?
  • 能否提供所有的Java类n Pom文件

标签: spring unit-testing spring-boot junit mockito


【解决方案1】:

通过阅读这两个 Stackoverflow 线程([1][2])以及 Spring documentation,您似乎应该将 Page 与存储库一起使用。示例:

PagingAndSortingRepository<User, Long> repository = // … get access to a bean
Page<User> users = repository.findAll(new PageRequest(1, 20));

对于您的情况,建议改用PagedListHolder。示例:

List<Movie> movieList = new ArrayList<>();
movieList.add(new Movie());
movieList.add(new Movie());
PagedListHolder<Movie> holder = new PagedListHolder<>(movieList);

【讨论】:

    【解决方案2】:

    您可以使用 Spring 的 mockMvc 对象将其注入到您的测试类中:

     @Autowired
     private MockMvc mockMvc;
    

    我刚刚创建了一个使用 mockMvc.perform 方法发送页面请求的测试方法:

    我的控制器代码:

    @GetMapping(produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public List<BaseResponse> listAllBase(
            @PageableDefault(size = 50, page = 2) Pageable pageable) {
    
        // logger.debug("paginación recibida :{}",pageable);
        List<BaseResponse> findAllBases = baseService.findAllBases();
        return findAllBases;
    
    }
    

    我的测试代码:

    mockMvc.perform(get("/base/?size=2&page=0")).andExpect(status().isOk())
                 .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))                        .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
                 .andExpect(jsonPath("$", hasSize(2)))                       .andExpect(jsonPath("$", hasSize(2)))
                 .andExpect(jsonPath("$[0].name", equalToIgnoringCase("margarita")))
    

    在我的 GitHub 存储库中查看完整的类代码:

    控制器:

    https://github.com/cristianprofile/spring-boot-mvc-complete-example/blob/develop/spring-boot-mvc-rest/src/main/java/com/mylab/cromero/controller/HelloWorldController.java#L53

    测试类方法:

    https://github.com/cristianprofile/spring-boot-mvc-complete-example/blob/develop/spring-boot-mvc-rest/src/test/java/com/mylab/cromero/controller/RestTestIT.java#L66

    随意在您的项目中使用它:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 2020-05-19
      • 2015-07-18
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多