Mvc controller test with session attribute

I am 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 that contains information about the user and is set in the session area when the user logs on to the system. But when I try to check:

 @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 that the userinfo class attribute is set by another method, so when I try to access it in this method, I got a NullPointerException and with Autowiring httpSession I got a new session for each method that I have to check.

What should I do with the session attribute, my method does not accept the session parameter, and for each test it creates a WebApplicationContext with a new session.

+3
spring-mvc junit4 attributes controller
Oct 13 '14 at 1:39 on
source share
1 answer

Try the following:

 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()); 
+11
Oct 13 '14 at 2:03
source share



All Articles