Java Spring集成测试依赖注入控制器

Java Spring集成测试依赖注入控制器,java,spring,dependency-injection,inversion-of-control,integration-testing,Java,Spring,Dependency Injection,Inversion Of Control,Integration Testing,我正在尝试为我的一个控制器类编写一个集成测试,该类中有一个注入依赖项。我尝试测试控制器中通过注入对象调用方法的部分,但是当我运行测试时,由于空指针异常,它失败了。在测试中,我使用了@ContexConfiguration和@RunsWith注释,但没有任何帮助。 一些代码可能会有所帮助:) AuthenticationController: @Controller public class AuthenticationController { @Resource(name = "use

我正在尝试为我的一个控制器类编写一个集成测试,该类中有一个注入依赖项。我尝试测试控制器中通过注入对象调用方法的部分,但是当我运行测试时,由于空指针异常,它失败了。在测试中,我使用了@ContexConfiguration和@RunsWith注释,但没有任何帮助。 一些代码可能会有所帮助:)

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";
        }
    }
在test-context.xml中:
bean: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");

       /* if UserForm is not valid */
        final BindingResult errors = assertAndReturnModelAttributeOfType(mav,
                "org.springframework.validation.BindingResult.user",
                BindingResult.class);
        assertTrue(errors.hasErrors());
        assertViewName(mav, "login");
    }
stacktrace告诉我错误发生在测试调用注入的userMangaement对象的登录方法的地方。um=null,因此注入无法与测试一起工作。 控制器在使用中工作良好

任何评论都会有很大帮助

提前感谢,


Sorex

如果需要autowire依赖项,则不能像这样创建控制器:

controller = new AuthenticationController();
您可以将依赖项自动关联到测试中

@Autowired
private UserManagement um;
并在控制器中创建构造函数,以便能够执行以下操作:

@Before
public void setUp() {
   controller = new AuthenticationController(um);
}
但我建议使用MockServletContext

MockServletContext mockServletContext = new MockServletContext();
mockServletContext.addInitParameter("contextConfigLocation", "path to your xml config"));
ContextLoaderListener listener = new ContextLoaderListener();
listener.initWebApplicationContext(mockServletContext);
还应该在某处参考DispatcherServlet。我从来没有在servlet环境中这样做过,只是在SpringPortletMVC中,但它应该是类似的。其想法是创建虚假的web应用程序上下文,并调用dispacher servlet在控制器和spring配置之间进行完全集成测试