Search code examples
springmockitostub

Mockito Page<> test return null


I'm testing controller using mockito. Even though I stubbed about the getBoardList, It doesn't initiate the method.

This is the controller. getBoardList() doesn't initiate when I checked in debug mode.

@GetMapping
public String getBoardListView(@Valid @Nullable BoardDto.Request request,
                               @PageableDefault(size = 10, sort = "createdAt", direction = Sort.Direction.ASC) Pageable pageable,
                               ModelMap map) {
    Page<BoardDto.Response> boardList = postService.getBoardList(request, pageable);

    map.addAttribute("boardList", boardList);
    return "board/index";
}

This is the controllerTest

@MockBean private PostService postService;

@Test
void getBoardListView() throws Exception {

    Page<BoardDto.Response> mock = Mockito.mock(Page.class);
    when(postService.getBoardList(eq(null), any(Pageable.class))).thenReturn(mock);

    mockMvc.perform(get("/board").with(csrf()))
            .andExpect(status().isOk())
            .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML))
            .andExpect(model().attributeExists("boardList"))
            .andExpect(view().name("board/index"));

    then(postService).should().getBoardList(any(BoardDto.Request.class), any(Pageable.class));
}

This is PostService interface.

public interface PostService {

    Page<BoardDto.Response> getBoardList(BoardDto.Request request, Pageable pageable);
}

This is PostServiceImpl

@RequiredArgsConstructor
@Transactional(readOnly = true)
@Service
public class PostServiceImpl implements PostService {

    private final PostRepository postRepository;

    @Override
    public Page<BoardDto.Response> getBoardList(BoardDto.Request request, Pageable pageable) {
        return postRepository.findBoardList(request, pageable).map(BoardDto.Response::from);
    }

}


Solution

  • Instead of:

    when(postService.getBoardList(eq(null) ...
    

    try:

    when(postService.getBoardList(any(BoardDto.Request.class)