rest - Spring-boot 使用可分页测试休息 Controller

标签 rest spring-boot junit spring-data-jpa mockito

我正在尝试测试以下 Controller :

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

这是测试类:

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

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

java.lang.AssertionError: Status 
Expected :200
Actual   :500

当我测试 URL http://localhost:8080/movies 时,它工作正常。

最佳答案

我认为您没有正确模拟/初始化您的 TitleService 这就是您收到 500 响应代码的原因。

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

@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


}  

或者:

@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

}  

关于rest - Spring-boot 使用可分页测试休息 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777116/

相关文章:

javascript - 如何在 MarkLogic JSON 中搜索文件中特定路径处的键值?

regex - 从 Varnish 中获取 url 值

spring-boot - spring-boot-starter-parent 版本 2 与 spring-security-jwt 和 spring-security-oauth2 之间是否有冲突

使用 livedata 进行 Android View 模型单元测试

javascript - 如何在 Sharepoint 中获取文件的文件类型

rest - 一般与特定端点 - Restful API 设计

java - Springboot + MySQL + 找不到驱动类

spring - 我如何等待Mono完成,以便可以利用生成的值

java - 如何使用 JMockit 或其他机制检查方法中局部变量的值

java - 警告 : The method assertEquals from the type Assert is deprecated