spring Mockito Page〈>测试返回空值

gmxoilav  于 2022-12-21  发布在  Spring
关注(0)|答案(2)|浏览(176)

我正在使用mockito测试控制器。尽管我对getBoardList做了存根,但它并没有启动该方法。
这是控制器。当我在调试模式下检查时,getBoardList()没有启动。

@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";
}

这是控制器测试

@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));
}

这是PostService接口。

public interface PostService {

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

这是后期服务实现

@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);
    }

}

vktxenjb

vktxenjb1#

取代:

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

尝试:

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

41zrol4v2#

如果要匹配空参数,请使用ArgumentMatchers#isNull,而不是eq(null)

when(postService.getBoardList(isNull(), any(Pageable.class))).thenReturn(mock);

相关问题