I am trying ot write an integration test for one of my controller classes which have an injected dependency in it. I try to test the part of my controller where it's calling a method through the injected object, but when i run my test its failing due to a null pointer exception. At the test i used @ContexConfiguration and @RunsWith annotations, but it didin't helped. Some code might help :)
AuthenticationController:
@Controller public class AuthenticationController { @Resource(name = "userManagement") private UserManagement um; @RequestMapping(method = RequestMethod.POST) public String onSubmit(@ModelAttribute("user") UserForm user, BindingResult result, Model model, HttpSession session) { LoginFormValidator validator = new LoginFormValidator(); validator.validate(user, result); if (result.hasErrors()) { return "login"; } else { User u = um.login(user.getEmail(), user.getPwd()); if (u != null) { session.setAttribute("user", u); LOGGER.info("succesful login with email: " + u.getEmail()); model.addAttribute("result", "succesful login"); } else { model.addAttribute("result", "login failed"); } return "result"; } } in test-context.xml: beans:bean id="userManagement" class="my.packages.UserManagement"
AuthenticationControllerTest:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"test-context.xml" }) public class AuthenticationControllerTest { private MockHttpServletRequest request; private MockHttpServletResponse response; private AuthenticationController controller; @Before public void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); controller = new AuthenticationController(); } @Test public void testLoginPost() throws Exception { request.setMethod("POST"); request.setRequestURI("/login"); request.setParameter("email", "[email protected]"); request.setParameter("pwd", "test"); final ModelAndView mav = new AnnotationMethodHandlerAdapter() .handle(request, response, controller); final UserForm u = assertAndReturnModelAttributeOfType(mav, "user", UserForm.class); assertEquals("[email protected]", u.getEmail()); assertEquals("test", u.getPwd()); assertViewName(mav, "result"); /* if UserForm is not valid */ final BindingResult errors = assertAndReturnModelAttributeOfType(mav, "org.springframework.validation.BindingResult.user", BindingResult.class); assertTrue(errors.hasErrors()); assertViewName(mav, "login"); } The stacktrace tells me that the error happens where the test calls the login method of the injected userMangaement object. um = null so the injection is not working with the test. The controller works fine in useage.
Any comment would help a lot!
Thanks in advance,
Sorex