I am trying to write an integration test for one of my controller classes that has a nested dependency. I try to check part of my controller when it calls a method through an injected object, but when I run my test, it crashes due to a null pointer exception. In the test, I used @ContexConfiguration and @RunsWith annotations, but this did not help. 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", " test@email.com "); request.setParameter("pwd", "test"); final ModelAndView mav = new AnnotationMethodHandlerAdapter() .handle(request, response, controller); final UserForm u = assertAndReturnModelAttributeOfType(mav, "user", UserForm.class); assertEquals(" test@email.com ", u.getEmail()); assertEquals("test", u.getPwd()); assertViewName(mav, "result"); final BindingResult errors = assertAndReturnModelAttributeOfType(mav, "org.springframework.validation.BindingResult.user", BindingResult.class); assertTrue(errors.hasErrors()); assertViewName(mav, "login"); }
The column tells me that the error occurs where the test calls the login method for the entered userMangaement object. um = null, so the injection does not work with the test. The controller works fine when used.
Any comment will help a lot!
Thanks in advance,
Sorex