Mockito.when method doesn't manage my service call

i'm trying to make Unit Test testing a simple GET controller method apply MockMvc.perform method but when the controller receive a request the method Mockito.when seems to doesn't manage the method call of MenuService and the test throw an exception. The Exception says menuServiceMock is null I'm working with Mockito MockMvc JUnit

import org.junit.runner.RunWith;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;

import edu.AG.LandingPageSanpietro.domain.Menu;
import edu.AG.LandingPageSanpietro.service.MenuService;

import java.util.Arrays;

import static org.hamcrest.Matchers.*;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;


@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
class MenuControllerTest {

private MockMvc mockMvc;

@Autowired
private MenuService menuServiceMock;


    @Test
    public void testHomeController1() throws Exception {
       Menu first=new Menu("titolo1","descrizione1","filename1");
       Menu second=new Menu("titolo2","descrizione2","filename2");

       Mockito.when(menuServiceMock.getMenus()).thenReturn(Arrays.asList(first, second));

       mockMvc.perform(get("/manageMenu"))
            .andExpect(status().isOk())
            .andExpect(view().name("manageMenu"))
            .andExpect(forwardedUrl("/src/main/resources/tamplates/manageMenu.html"))
            .andExpect(model().attribute("menus", hasSize(2)));

    }

My Controller

@GetMapping("/manageMenu")
public String chiamataGestisciMenu(Model model) {
     model.addAttribute("menus", menuService.getMenus());
    return "manageMenu";
}

The error

 java.lang.NullPointerException: Cannot invoke "edu.AG.LandingPageSanpietro.service.MenuService.getMenus()" because "this.menuServiceMock" is null
at edu.AG.LandingPageSanpietro.controller.MenuControllerTest.testHomeController1(MenuControllerTest.java:44)

I can't understand why when() method doesn't manage my menuServiceMock.getMenus() request for returning the specified list.


Use the annotation @Mock from mockito instead of @Autowired.