0

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?

Ankur Mukherjee
  • 3,777
  • 5
  • 32
  • 39

1 Answers1

0

FilterService is not a managed bean, you probably need to inject the dao in the constructor since it won't be autowired inside filterService.

Please refer to this question on SO for more info: Support for autowiring in a class not instantiated by spring (3)

Sadiq Ali
  • 1,272
  • 2
  • 15
  • 22