我正在尝试使用此签名测试方法:
@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");
}
Run Code Online (Sandbox Code Playgroud)
userinfo是一个类,其中包含有关用户的信息,并在用户登录时设置在会话范围内.但是当我尝试测试时:
@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());
}
Run Code Online (Sandbox Code Playgroud)
问题是userinfo类属性是在另一个方法中设置的,所以当我尝试在这个方法中访问它时,我得到了一个NullPointerException,并且通过自动装配httpSession,我为每个必须测试的方法获得了一个新的Session.
我应该如何处理session属性,我的方法不接受会话参数,并且对于每个测试,它都会创建一个带有新会话的WebApplicationContext.