When using mockito to unit test Spring mvc controller, how to inject dao layer object. It's always giving null pointer exception with @Spy annotation when making use of SpringJUnit4ClassRunner class.
Sample code:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:**/evivecare-application-context-test.xml" })
@WithMockUser(username = "admin", roles={"ADMIN"})
@TestExecutionListeners({DependencyInjectionTestExecutionListener.class})
public class ControllerTest {
private MockMvc mockMvc;
@Mock
private SessionFactory sessionFactory;
@Mock
private Session session;
@InjectMocks
private FilterController filterController = new FilterController();
@Spy
private FilterService filterService= new FilterServiceImpl();
@Autowired
private FilterDAO filterDAO;
@Mock
private OperatorService userService;
@Mock
private EviveSpeechFilterService eviveSpeechFilterService;
private TestContextManager testContextManager;
@Before
public void setup() throws Exception {
// Process mock annotations
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(filterController).build();
testContextManager = new TestContextManager(getClass());
testContextManager.prepareTestInstance(this);
filterDAO= new FilterDAOImpl(sessionFactory);
Mockito.doReturn(session).when(sessionFactory).getCurrentSession();
}
@Test
public void testController200() throws Exception{
Mockito.when(filterService.renameList("123","sdfgh")).thenReturn(false);
Mockito.when(filterDAO.renameList("123","sdfgh")).thenReturn(false);
this.mockMvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/renameList")
.sessionAttr("filterService", filterService)
.sessionAttr("filterDAO", filterDAO)
.param("listId", "1234567")
.param("alternateName", "LIst Name"))
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk());
}
}
In this test case, the filterService
in turn calls filterDAO
, which is always returning null pointer exception
.
So, what can I do to resolve this issue?