Meena Chaudhary
Meena Chaudhary

Reputation: 10665

Getting null for form parameter in Spring Test Framework Controller test

I am testing Sign Up form submit using Spring Test Framework. And I am passing parameters using param but parameter assertion is failing because value is coming out to be null. Below is the code

Controller:

@RequestMapping("/signup")
public ModelAndView signUp(@ModelAttribute(value = "signupForm") @Valid SignupForm form, BindingResult bResult) {
    ModelAndView mv = new ModelAndView();
    if (bResult.hasErrors()) {
        mv.setViewName("signupform");
        return mv;
    }
    mv.setViewName("home");
    userService.sigUpUser(form);
    return mv;
}

Controller Test for submit:

@Test
public void goSignupFormSubmit() throws Exception {

    this.mockMvc.perform(post("/signup").contentType(MediaType.APPLICATION_FORM_URLENCODED)
            .param("username", "[email protected]")
            .param("password", "somebody")
            .param("firstName", "somebody")
            .param("lastName", "kumar")
            ).andDo(print())
    .andExpect(status().isOk())
    .andExpect(view().name("home"))
    .andExpect(forwardedUrl("/WEB-INF/template/default.jsp"))
    .andExpect(model().attribute("username", is("[email protected]")))
    .andExpect(model().attribute("password", is("somebody")))
    .andExpect(model().attribute("firstName", is("somebody")))
    .andExpect(model().attribute("lastName", is("kumar")));

}

Test outcome:

java.lang.AssertionError: Model attribute 'username'
Expected: is "[email protected]"
 got: null

at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:21)
at org.springframework.test.web.servlet.result.ModelResultMatchers$1.match(ModelResultMatchers.java:58)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:166)
at com.saffron.controller.FrontControllerIT.goSignupFormSubmit(FrontControllerIT.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:85)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:86)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:241)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:87)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Print() output:

MockHttpServletRequest:
  HTTP Method = POST
  Request URI = /signup
   Parameters = {username=[[email protected]], password=[somebody], firstName=[somebody], lastName=[singh]}
      Headers = {Content-Type=[application/x-www-form-urlencoded]}

Handler:
         Type = com.saffron.controller.FrontController
       Method = public org.springframework.web.servlet.ModelAndView com.saffron.controller.FrontController.signUp(com.saffron.view.SignupForm,org.springframework.validation.BindingResult)

Async:
Async started = false
 Async result = null

Resolved Exception:
         Type = null

ModelAndView:
    View name = home
         View = null
    Attribute = signupForm
        value = signupForm [[email protected], password=somebody, firstName=somebody, lastName=singh]
       errors = []

FlashMap:
   Attributes = null

MockHttpServletResponse:
       Status = 200
Error message = null
      Headers = {}
 Content type = null
         Body = 
Forwarded URL = /WEB-INF/template/default.jsp
Redirected URL = null
      Cookies = []

Upvotes: 1

Views: 2413

Answers (1)

Meena Chaudhary
Meena Chaudhary

Reputation: 10665

Following worked for me. Below is the code for my controller and its corresponding controller tests. Hope it helps. Also not sure why this question was voted down.

Controller:

@RequestMapping("/signup")
public ModelAndView signUp(@ModelAttribute(value = "signupForm") @Valid SignupForm form, BindingResult bResult) {

    ModelAndView mv = new ModelAndView();
    if (bResult.hasErrors()) {
        mv.setViewName("signupform");
        return mv;
    }
    User user = userService.sigUpUser(form);
    mv.addObject("user", user);
    mv.setViewName("home");
    return mv;
}

To check form submission:

@Test
public void goSignupFormSubmit() throws Exception {

    this.mockMvc
            .perform(post("/signup").contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .param("username", "[email protected]").param("password", "somebody")
                    .param("firstName", "somebody").param("lastName", "kumar"))
            .andDo(print()).andExpect(status().isOk()).andExpect(view().name("home"))
            .andExpect(forwardedUrl("/WEB-INF/template/default.jsp"))
            .andExpect(model().attribute("signupForm", hasProperty("username", is("[email protected]"))))
            .andExpect(model().attribute("signupForm", hasProperty("password", is("somebody"))))
            .andExpect(model().attribute("signupForm", hasProperty("firstName", is("somebody"))))
            .andExpect(model().attribute("signupForm", hasProperty("lastName", is("kumar"))));

}

To check database insertion:

@Test
public void goSignupFormDatabaseInsertion() throws Exception {

    this.mockMvc
            .perform(post("/signup").contentType(MediaType.APPLICATION_FORM_URLENCODED)
                    .param("username", "[email protected]").param("password", "somebody")
                    .param("firstName", "somebody").param("lastName", "kumar"))
            .andExpect(status().isOk()).andExpect(view().name("home"))
            .andExpect(forwardedUrl("/WEB-INF/template/default.jsp"))
            .andExpect(model().attribute("user", hasProperty("username", is("[email protected]"))))
            .andExpect(model().attribute("user", hasProperty("password", is("somebody"))))
            .andExpect(model().attribute("user", hasProperty("enabled", is(1))))
            .andExpect(model().attribute("user", hasProperty("authority", hasProperty("username", is("[email protected]")))))
            .andExpect(model().attribute("user", hasProperty("authority", hasProperty("authorityType", is("candidate")))))
            .andExpect(model().attribute("user", hasProperty("userDetails", hasProperty("username", is("[email protected]")))))
            .andExpect(model().attribute("user", hasProperty("userDetails", hasProperty("firstName", is("somebody")))))
            .andExpect(model().attribute("user", hasProperty("userDetails", hasProperty("lastName", is("kumar")))));

}

Upvotes: 1

Related Questions