Announcement Announcement Module
Collapse
No announcement yet.
Test class unable to read from dispatcher-servlet.xml Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Test class unable to read from dispatcher-servlet.xml

    Hi Everybode,

    I'm trying to test my simple LoginController, but I'm getting NullPointerException whenever I try to use methods like getSuccessView(), getCommandClass(), getCommandName()!

    Here is my LoginContoller:
    Code:
    public class LoginController extends SimpleFormController{
        
        @Override
        public ModelAndView onSubmit(HttpServletRequest request,
                HttpServletResponse response,
                Object command,
                BindException errors)
                throws Exception {        
            Login login = (Login) command;
            System.out.println("The username is " + login.getUsername());
            System.out.println("the password is " + login.getPassword());
            request.getSession().setAttribute("login", login);
        	return new ModelAndView(new RedirectView(getSuccessView()));
        }
    }
    And here is my test class LoginControllerTest()
    Code:
    public class LoginControllerTest {
    
            private MockHttpServletRequest  request;
            private MockHttpServletResponse  response;
            private LoginController loginController;
        
        public LoginControllerTest() {
        }
    
        @BeforeClass
        public static void setUpClass() throws Exception {
        }
    
        @AfterClass
        public static void tearDownClass() throws Exception {
        }
    
        @Before
        public void setUp() {
            request = new MockHttpServletRequest();
            response = new MockHttpServletResponse();
            request.setMethod("GET");
            loginController = new LoginController();
        }
        @After
        public void tearDown() {
        }
        
        @Test
    	public void testCreate() {
    		assertEquals(Login.class, loginController.getCommandClass());   // <-------- This is returning NullPointerExecption
    		assertEquals("login", loginController.getCommandName()); //<------- This is returning NullPointerExecption
    		assertEquals("login", loginController.getFormView()); // <-------- This is returning NullPointerExecption
    		assertEquals("redirect:search.html", loginController.getSuccessView());
    	}
    
        /**
         * Test of onSubmit method, of class LoginController.
         */
        @Test
        public void testOnSubmit() throws Exception {
            System.out.println("onSubmit");
            LoginController loginController = new LoginController();
            
            Login login = new Login();
            login.setUsername("admin");
            login.setPassword("adminadmin");
            //BindException errors = new BindException(login, "errors");
            
            //request.getSession().setAttribute("login", login);
            ModelAndView mv = loginController.onSubmit(request, response, login, null);
            assertEquals("search.html", mv.getViewName()); // <------This is returning NullPointerExecption
        }
    And Here is the code regarding loginController in my dispatcher-servlet.xml
    Code:
        <bean name="loginController" class="se.spray.rico.web.LoginController">
            <property name="commandClass" value="se.spray.rico.model.Login"/>
            <property name="formView" value="login"/>
            <property name="successView" value="search.html"/>
            <property name="validator" ref="loginValidatorManager"/>
            <property name="commandName" value="login"/>
            <property name="sessionForm" value="true"/>
        </bean>
    I'll be very thankful is somebode could point to me what I'm doing wrong?

    Regards
    Azam

  • #2
    Actually, I have just noticed that getSuccessView() at the last line in my loginController
    Code:
    return new ModelAndView(new RedirectView(getSuccessView()));
    is returning null. That's why
    Code:
    assertEquals("search.html", mv.getViewName());
    at the last line in my loginControllerTest is returning NullPointerException.
    BUT STILL! The LoginController works fine. Why do getSuccessView() thorw NullpointerExecption when testing?

    OBS! I have commited away the testCreate() method in LoginControllerTest and this is what I'm getting when testing

    Code:
    ------------- Standard Output ---------------
    onSubmit
    The username is admin
    the password is adminadmin
    mv.getViewNamenull
     my mv ModelAndView: materialized View is [org.springframework.web.servlet.view.RedirectView: unnamed; URL [null]]; model is null
    ------------- ---------------- ---------------
    ------------- Standard Error -----------------
    log4j:WARN No appenders could be found for logger (org.springframework.util.ClassUtils).
    log4j:WARN Please initialize the log4j system properly.
    ------------- ---------------- ---------------
    Testcase: testOnSubmit(se.spray.rico.web.LoginControllerTest):	FAILED
    expected:<search.html> but was:<null>
    junit.framework.AssertionFailedError: expected:<search.html> but was:<null>
            at se.spray.rico.web.LoginControllerTest.testOnSubmit(LoginControllerTest.java:86)
    Regards
    Azam

    Comment


    • #3
      are you sure that you properly bound the spring application context to your test class ???

      Im missing something that looks like (junit 4.4)
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(locations={"/application-context.xml"})
      public class LoginControllerTest{ ...
      }

      The npe might be thrown due to misconfiguration of junit test.

      Have a look at http://static.springframework.org/sp...e/testing.html

      Comment


      • #4
        Hi tmaus,

        I noticed the annotations you were talking about, but do I have to use annotation-driven JUnit testing? or is it just one alternativ of tesing?
        Because I know nothing about annotations and how they are used, and I don't have enough time in my project to sitt down and learn about annotation, not for the moment.....

        Is there another way to bind LoginControllerTest to the dispatcher-servlet.xml without using annotations?

        I cannot find what is wrong with my solution?
        getSuccessView() works perfectly when I'm not tesing. I printed out its value and it returned searh.html.
        When testing, it is returning null.

        Regards
        Azam

        Comment


        • #5
          have a look at this chapter:
          http://static.springframework.org/sp...acy-fixture-di

          whatever you do with spring .. the very basic is the documentation.

          The aforementioned chapter allows you to setup a test without annotations.

          Give it a try

          Comment


          • #6
            Hi again tmaus

            I followed you tip regarding using AbstractDependencyInjectionSpringContextTests and I received exaclly the same results as before.....

            getSuccessView() working fine in my LoginController and returning the view name search.html, but as soon as I start testing and run LoginControllerTest, getSuccessView() at LoginController starts returning null instead.



            Regards
            Azam

            Comment


            • #7
              I have now tried annotations and still getting the same results

              Code:
              @RunWith(SpringJUnit4ClassRunner.class)
              @ContextConfiguration(locations={"classpath:rico-test.xml"})
              public class LoginControllerTest{
              
                  private MockHttpServletRequest request;
                  private MockHttpServletResponse response;
                  @Autowired
                  private LoginController loginController;
              
                  @BeforeClass
                  public static void setUpClass() throws Exception {
                  }
              
                  @AfterClass
                  public static void tearDownClass() throws Exception {
                  }
              
                  @Before
                  public void setUp() {
                      request = new MockHttpServletRequest();
                      response = new MockHttpServletResponse();
                      request.setMethod("GET");
                      loginController = new LoginController();
                  }
              
                  @After
                  public void tearDown() {
                  }
              
                  /**
                   * Test of onSubmit method, of class LoginController.
                   */
                  @Test
                  public void testOnSubmit() throws Exception {
                      System.out.println("onSubmit");
                      request.setMethod("GET");
              
                      Login login = new Login();
                      login.setUsername("admin");
                      login.setPassword("adminadmin");
                      //BindException errors = new BindException(login, "errors");
              
                     // request.getSession().setAttribute("login", login);
                      ModelAndView mv = loginController.onSubmit(request, response, login, null);
                      System.out.println("mv.getViewName" + mv.getViewName());
                      System.out.println(" my mv " + mv);
                      assertEquals("search.html", mv.getViewName());
              
              
                  }
              }
              rico-test.xml
              Code:
              <beans xmlns="http://www.springframework.org/schema/beans" 
                     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                     xsi:schemaLocation="http://www.springframework.org/schema/beans 
                         http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
              
                  <!-- this bean will be injected into the HibernateTitleDaoTests class -->
                  <bean id="loginController" class="se.spray.rico.web.LoginController"/>
              
              
              </beans>
              Still the same error
              Code:
              Testsuite: se.spray.rico.web.LoginControllerTest
              onSubmit
              The username is admin
              the password is adminadmin
               getSuccessView null
              mv.getViewNamenull
               my mv ModelAndView: materialized View is [org.springframework.web.servlet.view.RedirectView: unnamed; URL [null]]; model is null
              Tests run: 1, Failures: 1, Errors: 0, Time elapsed: 0,324 sec
              
              ------------- Standard Output ---------------
              onSubmit
              The username is admin
              the password is adminadmin
               getSuccessView null
              mv.getViewNamenull
               my mv ModelAndView: materialized View is [org.springframework.web.servlet.view.RedirectView: unnamed; URL [null]]; model is null
              ------------- ---------------- ---------------
              ------------- Standard Error -----------------
              log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
              log4j:WARN Please initialize the log4j system properly.
              ------------- ---------------- ---------------
              Testcase: testOnSubmit(se.spray.rico.web.LoginControllerTest):	FAILED
              expected:<search.html> but was:<null>
              junit.framework.AssertionFailedError: expected:<search.html> but was:<null>
                      at org.springframework.test.context.junit4.SpringMethodRoadie.addFailure(SpringMethodRoadie.java:320)
                      at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:242)
                      at org.springframework.test.context.junit4.SpringMethodRoadie$RunBeforesThenTestThenAfters.run(SpringMethodRoadie.java:333)
                      at org.springframework.test.context.junit4.SpringMethodRoadie.runWithRepetitions(SpringMethodRoadie.java:217)
                      at org.springframework.test.context.junit4.SpringMethodRoadie.runTest(SpringMethodRoadie.java:197)
                      at org.springframework.test.context.junit4.SpringMethodRoadie.run(SpringMethodRoadie.java:143)
                      at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:142)
                      at se.spray.rico.web.LoginControllerTest.testOnSubmit(LoginControllerTest.java:76)
                      at org.springframework.test.context.junit4.SpringTestMethod.invoke(SpringTestMethod.java:163)
                      at org.springframework.test.context.junit4.SpringMethodRoadie.runTestMethod(SpringMethodRoadie.java:233)
              What am I doing wrong?

              Regards
              Azam

              Comment


              • #8
                Hi everybody,

                I think it is a container related problem! But still don't know how to solve it!
                Maybe that I have to hardcode where to find the xml file localy and not on server......and by hardcoded I mean using absolute path and not relative path

                regards
                azam

                Comment


                • #9
                  So you have to dive a bit deeper into spring.
                  You first of all need to get rid of these two lines:
                  log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUn it4ClassRunner).
                  log4j:WARN Please initialize the log4j system properly.

                  Add a proper log4j.xml (or .properties) and take care that spring finds it during bootstrap.
                  Proper samples can be found everywhere.
                  Take care that you log in debug level all spring related packages.
                  Restart your test.
                  Open the logfile (if not logged into the console) and grep for "rico-test.xml"
                  You first of all need to asure that your bean configuration is properly loaded prior doing anything else.
                  Second ... if working with annotations you have to tell spring that annotations are accepted.
                  Have a look at this chapter and complement your rico-test.xml file accordingly.

                  Comment


                  • #10
                    Hi,
                    can you please post your security spring configuration for this in your onSubmit method

                    request.getSession().setAttribute("login", login);


                    I cant figure out how it maps with <http> element and
                    <authentication-provider>
                    <user-service>
                    <user name="user" password="pass" authorities="ROLE_USER" />
                    </user-service>
                    </authentication-provider>


                    because I have my user&pass in my LogonControler, but I am always ANONYMUS_USER insted of ROLE_USER.


                    Thanks.

                    Comment

                    Working...
                    X