2
votes

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.

1

1 Answers

6
votes

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

You can fix it by mocking the TitleService and passing it to your tested 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


}  

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

}