Java 向会话添加属性的测试方法失败

Java 向会话添加属性的测试方法失败,java,junit,mockito,portlet,Java,Junit,Mockito,Portlet,我正在测试一个只向portletsession添加属性的方法,代码如下: @Test @PrepareForTest({ActionRequest.class, ActionResponse.class, LocalizedLoggerFactory.class}) public void test_addConfigCookiesFromSession() { PowerMockito.mockStatic(LocalizedLoggerFactory.

我正在测试一个只向portletsession添加属性的方法,代码如下:

    @Test
    @PrepareForTest({ActionRequest.class, ActionResponse.class, LocalizedLoggerFactory.class})
    public void test_addConfigCookiesFromSession() {
        PowerMockito.mockStatic(LocalizedLoggerFactory.class);
        ActionRequest request = PowerMockito.mock(ActionRequest.class);
        PortletSession session = PowerMockito.mock(PortletSession.class);
        when(request.getPortletSession()).thenReturn(session);

        List<String> list = new ArrayList<String>();
        list.add("prueba");
        ConfigPortlet configPortlet = new ConfigPortlet();
        configPortlet.addCookiesToSession(request, list);

        assertNotNull(session.getAttribute("exemptCookiesListSession"));
    }
但是当我执行断言时,session.getattribute中有null。我做错了什么?

您的“session”变量是一个模拟对象。在模拟对象上调用“setAttribute()”时,它不会执行任何操作。之后调用“getAttribute()”将无法获得在调用“setAttribute()”时发送的值

听起来您需要的是这样的东西(使用mockito的静态导入):


尝试getProperty而不是getAttribute,尝试setProperty而不是SetAttribute。
PortletSession portletSession = request.getPortletSession();
        portletSession.setAttribute("exemptCookiesListSession", listExemptCookies);
verify(session).setAttribute(eq("exemptCookiesListSession"), anyList());