java - HttpSession Junit 测试
问题描述
我不能模拟 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,但我需要避免它。如何为会话添加一些参数来模拟工作?
解决方案
您应该在配置时使用相关的会话方法来配置会话状态。在MockHttpServlet
内部,它将MockHttpSession
为MockHttpServlet
您正在构建的创建一个。
mockMvc.perform(get("/feed")
.sessionAttr("loginStatus", true)
.sessionAttr("userId", 1234l))
.andExpect(status().isOk())
.andExpect(view().name("posts/feed"))
.andExpect(model().attributeExists("posts"));
推荐阅读
- blockchain - Corda:出现错误 - CollectSignaturesFlow 的发起者必须准确传递签署交易所需的会话
- swift - 过滤数组时性能迅速下降
- apache-kafka - 屏蔽kafka连接器的日志
- c - 如何使用条件和循环来模拟 Monty Hall 问题?
- assembly - MIPs 程序集中数组的最大值
- php - Wp add_shortcode 属性不改变属性值
- google-apps-script - 谷歌脚本:我们如何使用脚本提取标签的超链接,在您的 Google 表格公式栏上看不到它的 URL?
- python - 如何将 SQLAlchemy 会话传递给多处理函数?
- java - Jasypt 加密异常:线程“主”java.lang.NoClassDefFoundError 中的异常:org/jasypt/encryption/StringEncryptor
- delphi - delphi如何获取数据并在Tgrid中显示