我不能在HttpSession上做模拟。测试方法如下所示:
@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"));
}我总是得到UnauthorizedException,但我需要避免它。如何为session添加一些参数来模拟工作?
发布于 2019-09-11 15:46:27
在配置MockHttpServlet .Internally的过程中,您应该使用相关的会话方法来配置会话状态,它将为您正在构建的MockHttpServlet创建一个MockHttpSession。
mockMvc.perform(get("/feed")
.sessionAttr("loginStatus", true)
.sessionAttr("userId", 1234l))
.andExpect(status().isOk())
.andExpect(view().name("posts/feed"))
.andExpect(model().attributeExists("posts"));https://stackoverflow.com/questions/57883910
复制相似问题