gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 17:44:50 26 4
gpt4 key购买 nike

我正在尝试测试以下 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com