java - HttpSession 联合测试

标签 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("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 添加一些参数来模拟工作?

最佳答案

在配置 MockHttpServlet 时,您应该使用相关的 session 方法来配置 session 状态。在内部,它会为 MockHttpServlet 创建一个 MockHttpSession > 您正在构建。

 mockMvc.perform(get("/feed")
           .sessionAttr("loginStatus", true)
           .sessionAttr("userId", 1234l))
                .andExpect(status().isOk())
                .andExpect(view().name("posts/feed"))
                .andExpect(model().attributeExists("posts"));

关于java - HttpSession 联合测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57883910/

相关文章:

java - Mockito verify(...) 失败 - "Actually, there were zero interactions with this mock."在多次连续测试中运行

java - 使用 Mockito 来 stub 与被测类 (CUT) 相同的类中的方法

java - 创建实体标签,但它为空

java - 如何在guice中获取字符串实例

java - 如何为无效返回方法定义 AnswersWithDelay

java - 单元测试与行为相关的私有(private)字段

javascript - Sinon stub 是如何工作的?

java - 我如何知道我的服务何时从广播接收器与 Android 调用?

java - 如何在 Spring Boot 中从 application.properties 分配注释值?

mocking - 生成的服务模拟 : everything but RhinoMocks fails?