Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting session attributes for JUnits on Spring 3.2

I'm having trouble setting session attributes for a test. I am using MockMvc to test calls to a controller. The session model has a member attribute on it (representing the person who has logged in). The SessionModel object is added as a session attribute. I was expecting it to be populated in the ModelMap parameter to formBacking method below, but the ModelMap is always empty.

The controller code works fine when running through the webapp, but not in the JUnit. Any idea what I could be doing wrong?

Here is my JUnit Test

@Test
  public void testUnitCreatePostSuccess() throws Exception {

    UnitCreateModel expected = new UnitCreateModel();
    expected.reset();
    expected.getUnit().setName("Bob");

    SessionModel sm = new SessionModel();
    sm.setMember(getDefaultMember());

    this.mockMvc.perform(
        post("/units/create")
        .param("unit.name", "Bob")
        .sessionAttr(SessionModel.KEY, sm))
        .andExpect(status().isOk())
        .andExpect(model().attribute("unitCreateModel", expected))
        .andExpect(view().name("tiles.content.unit.create"));

  }

and here is the controller in question

@Controller
@SessionAttributes({ SessionModel.KEY, UnitCreateModel.KEY })
@RequestMapping("/units")
public class UnitCreateController extends ABaseController {

  private static final String CREATE = "tiles.content.unit.create";

  @Autowired
  private IUnitMemberService unitMemberService;

  @Autowired
  private IUnitService unitService;

  @ModelAttribute
  public void formBacking(ModelMap model) {

    SessionModel instanceSessionModel = new SessionModel();
    instanceSessionModel.retrieveOrCreate(model);

    UnitCreateModel instanceModel = new UnitCreateModel();
    instanceModel.retrieveOrCreate(model);
  }

  @RequestMapping(value = "/create", method = RequestMethod.GET)
  public String onCreate(
      @ModelAttribute(UnitCreateModel.KEY) UnitCreateModel model, 
      @ModelAttribute(SessionModel.KEY) SessionModel sessionModel) {

    model.reset();

    return CREATE;
  }

  @RequestMapping(value = "/create", method = RequestMethod.POST)
  public String onCreatePost(
      @ModelAttribute(SessionModel.KEY) SessionModel sessionModel,
      @Valid @ModelAttribute(UnitCreateModel.KEY) UnitCreateModel model, 
      BindingResult result) throws ServiceRecoverableException {

    if (result.hasErrors()){
      return CREATE;
    }

    long memberId = sessionModel.getMember().getId();

    long unitId = unitService.create(model.getUnit());
    unitMemberService.addMemberToUnit(memberId, unitId, true);

    return CREATE;
  }

}
like image 912
Ash McConnell Avatar asked Jan 09 '13 10:01

Ash McConnell


People also ask

What is session attribute in spring?

SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation.

How do I create a session attribute?

The client can create session attributes in a request by calling either the PostContent or the PostText operation with the sessionAttributes field set to a value. A Lambda function can create a session attribute in a response.

What are session attributes?

A session attribute is a pre-defined variable that is persistent throughout the life of a Tealeaf session. Session attributes can be used to store various data that may be referenced by events at any point during the session.

How session is maintained in Spring MVC?

Have a look at the @SessionAttributes annotation, which allows you to define the attributes that will be stored in the session by your controller; this mechanism is mainly intended to maintain the conversational state for your handler and that state is usually cleared once the conversation is complete.


1 Answers

For your test class add the @WebAppConfiguration annotation and autowire the following as well.(WebApplicationContext and MockHttpSession )

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration({ "classpath:springDispatcher-servlet.xml" })
public class MySessionControllerTest {
    @Autowired WebApplicationContext wac; 
    @Autowired MockHttpSession session;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testUnitCreatePostSuccess() throws Exception {
        UnitCreateModel expected = new UnitCreateModel();
        expected.reset();
        expected.getUnit().setName("Bob");

        SessionModel sm = new SessionModel();
        sm.setMember(getDefaultMember());
        session.setAttribute(SessionModel.KEY, sm);
        this.mockMvc.perform(
            post("/units/create")
            .session(session)
            .param("unit.name", "Bob")
            .andExpect(status().isOk())
            .andExpect(model().attribute("unitCreateModel", expected))
            .andExpect(view().name("tiles.content.unit.create"));

  }
}
like image 121
Manuel Quinones Avatar answered Oct 01 '22 15:10

Manuel Quinones