首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HttpSession Junit测试

HttpSession Junit测试
EN

Stack Overflow用户
提问于 2019-09-11 15:11:46
回答 1查看 134关注 0票数 0

我不能在HttpSession上做模拟。测试方法如下所示:

代码语言:javascript
复制
@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";
    }

测试看起来是这样的:

代码语言:javascript
复制
 @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添加一些参数来模拟工作?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-09-11 15:46:27

在配置MockHttpServlet .Internally的过程中,您应该使用相关的会话方法来配置会话状态,它将为您正在构建的MockHttpServlet创建一个MockHttpSession

代码语言:javascript
复制
 mockMvc.perform(get("/feed")
           .sessionAttr("loginStatus", true)
           .sessionAttr("userId", 1234l))
                .andExpect(status().isOk())
                .andExpect(view().name("posts/feed"))
                .andExpect(model().attributeExists("posts"));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/57883910

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档