mvc controller test with session attribute

Alex2330 picture Alex2330 · Oct 13, 2014 · Viewed 10.7k times · Source

I'm trying to test a method with this signature:

 @Autowired
HttpSession http_Session;
@RequestMapping(method=RequestMethod.GET, value="/search/findByName")
public @ResponseBody List<Map> search(@RequestParam(value="name", required=true) String name){
Integer user_id = http_Session.getAttribute("userinfo");
}

userinfo is a class which contains informations about the user and set in session scope when the user logged in.but when I try the test :

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration 
@ContextConfiguration(locations = {
   "classpath:/META-INF/applicationContext.xml"})

 public class userControllerTest {

private MockMvc mockMvc;  
@Autowired
private WebApplicationContext webApplicationContext;

@Before 
public void setUp() {
    MockitoAnnotations.initMocks(this);
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
 }  
 @Test
 public void userTest() throws Exception {
     mockMvc.perform(MockMvcRequestBuilders.get("/search/findByName").param("name", "bob"))
          .andDo(print())
          .andExpect(MockMvcResultMatchers.status().isOk());
    }

The problem is the userinfo class attribute is set in another method so when i try to access it in this method i got a NullPointerException , and with Autowiring the httpSession i got a new Session for each method i have to test.

What should i do with the session attribute, my method doesn't accept a session parameter , and for each test it create a WebApplicationContext with a new session.

Answer

jpprade picture jpprade · Oct 13, 2014

Try this :

HashMap<String, Object> sessionattr = new HashMap<String, Object>();
sessionattr.put("userinfo", "XXXXXXXX");

mockMvc.perform(MockMvcRequestBuilders.get("/search/findByName").sessionAttrs(sessionattr).param("name", "bob"))
          .andDo(print())
          .andExpect(MockMvcResultMatchers.status().isOk());