Java HttpSession Junit测试
我不能在HttpSession上进行模拟。测试方法如下所示:Java HttpSession Junit测试,java,mocking,mockito,junit4,Java,Mocking,Mockito,Junit4,我不能在HttpSession上进行模拟。测试方法如下所示: @GetMapping @RequestMapping("/feed") public String feed(HttpSession session, Model model) throws UnauthorizedException { if (session.getAttribute("loginStatus") == null) throw new UnauthorizedException("
@GetMapping
@RequestMapping("/feed")
public String feed(HttpSession session, Model model) throws UnauthorizedException {
if (session.getAttribute("loginStatus") == null) throw new UnauthorizedException("You have to login first");
Long userId = (Long) session.getAttribute("userId");
model.addAttribute("posts", postService.feed(userId));
return "posts/feed";
}
测试结果如下所示:
@Mock
private PostService postService;
private MockMvc mockMvc;
private PostViewController controller;
@Mock
private HttpSession session;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
controller = new PostViewController(postService);
mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
}
@Test
public void feed() throws Exception {
when(session.getAttribute("loginStatus")).thenReturn(true);
mockMvc.perform(get("/feed"))
.andExpect(status().isOk())
.andExpect(view().name("posts/feed"))
.andExpect(model().attributeExists("posts"));
}
我总是有未经授权的感觉,但我需要避免它。如何为会话添加一些参数以模拟工作?在配置
MockHttpServlet
期间,您应该使用相关的会话方法来配置会话状态。在内部,它将为您正在构建的MockHttpServlet
创建一个MockHttpSession
mockMvc.perform(get(“/feed”)
.sessionatr(“loginStatus”,真)
.sessionatr(“用户ID”,1234l))
.andExpect(状态().isOk())
.andExpect(view().name(“posts/feed”))
.andExpect(model().attributeExists(“posts”));