Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7595037
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T21:34:16+00:00 2026-05-30T21:34:16+00:00

I am trying ot write an integration test for one of my controller classes

  • 0

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", "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");
    }

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

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T21:34:18+00:00Added an answer on May 30, 2026 at 9:34 pm

    If you want autowire dependencies you can’t create your controller like this:

    controller = new AuthenticationController();
    

    You can autowire you dependency into your test

    @Autowired
    private UserManagement um;
    

    and create constructor in your controller to be able to do this:

    @Before
    public void setUp() {
       controller = new AuthenticationController(um);
    }
    

    But I would recommend to use MockServletContext.

    MockServletContext mockServletContext = new MockServletContext();
    mockServletContext.addInitParameter("contextConfigLocation", "path to your xml config"));
    ContextLoaderListener listener = new ContextLoaderListener();
    listener.initWebApplicationContext(mockServletContext);
    

    There should be also reference to DispatcherServlet somewhere. I have never done this in servlet environmentm, only in spring portlet mvc, but it shoul be similar. The idea is to create fake web application context and call dispacher servlet to have full integration test between your controllers an spring configuration.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I was trying to write an integration test testing, if my controller raises a
I'm trying write a query to find records which don't have a matching record
I am trying to write a simple integration test on a Rails 3.1 application
I am trying to write an integration test POM for our project. We've got
I'm trying to write spec for inherited_resources controller. I decided to mock all integration
I'm trying to write a Sign in integration test for my app + devise
I'm attempting to write an integration test using the OCUnit/SenTest Framework which I feel
I'm trying to write a simple integration test, but having some trouble with Domain
I'm trying to write a test for the Jasmine Test Framework which expects an
I'm trying to create automated integration tests for this hardware+software test subject which runs

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.