Spring-boot testing a rest controller with pageable

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Spring-boot testing a rest controller with pageable



I'm trying to test the following controller:


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



and here's the test class:


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




When i run the test it fails and gives me the following message:


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



When i test the url http://localhost:8080/movies it works properly.


http://localhost:8080/movies




1 Answer
1



I think you didn't properly mock/initialize your TitleService that's why you are getting 500 response code.


TitleService


500



You can fix it by mocking the TitleService and passing it to your tested controller:


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





Or:


@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







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS