Spring-boot测试具有可分页的休息控制器

K. *_*oub 2 rest junit mockito spring-data-jpa spring-boot

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

@GetMapping("movies")
public Page<Title> getAllMovies(@PageableDefault(value=2) Pageable pageable){        
    return this.titleService.getTitleByType("Movie", pageable);
}
Run Code Online (Sandbox Code Playgroud)

这是测试类:

@RunWith(SpringRunner.class)
@WebMvcTest(TitleController.class)
@EnableSpringDataWebSupport
public class TitleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockBean
    private TitleService titleService;

    // Test controller method - getAllMovies
    @Test
    public void getAllMovies() throws Exception {
        Title title = new Title();
        title.setId((short)1);
        title.setName("The Godfather");
        title.setType("Movie");    

        List<Title> titles = new ArrayList<>();
        titles.add(title);
        Page<Title> page = new PageImpl<>(titles);

        given(this.titleService.getTitleByType("Movie", PageRequest.of(0,2))).willReturn(page);
        mockMvc.perform(MockMvcRequestBuilders.get("/movies"))
                .andExpect(status().isOk());
    }
}  
Run Code Online (Sandbox Code Playgroud)

当我运行测试时它失败并给我以下消息:

java.lang.AssertionError: Status 
Expected :200
Actual   :500
Run Code Online (Sandbox Code Playgroud)

当我测试网址时,http://localhost:8080/movies它正常工作.

Mar*_*cki 6

我认为您没有正确地模拟/初始化您TitleService的原因,这就是您获得500响应代码的原因.

您可以通过模拟TitleService并将其传递给测试的控制器来修复它:

@RunWith(SpringJUnit4ClassRunner.class)
public class TitleControllerTest {

    private MockMvc mockMvc;

    private TitleController underTest;

    @Mock
    private TitleService titleService;

    @Before
    public void init() {
        underTest = new TitleController(titleService);

        //DO THE MOCKING ON TITLE SERVICE
        // when(titleService.getTitleByType()) etc.

        mockMvc = MockMvcBuilders
                .standaloneSetup(underTest)
                .build();
    }

    //your tests


}  
Run Code Online (Sandbox Code Playgroud)

要么:

@RunWith(SpringRunner.class)
@WebMvcTest(TitleController.class)
@EnableSpringDataWebSupport
public class TitleControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private TitleController titleController;

    @MockBean
    private TitleService titleService;

    @Before
    public void init() {
        titleController.setTitleService(titleService);

        //DO THE MOCKING ON TITLE SERVICE
        // when(titleService.getTitleByType()) etc.
    }

    //your tests

}  
Run Code Online (Sandbox Code Playgroud)