【问题标题】:How to mock HttpSession in JSF如何在 JSF 中模拟 HttpSession
【发布时间】:2013-11-02 22:24:07
【问题描述】:

我有一个获取会话属性的服务方法,我想对该服务方法进行单元测试,我想知道如何在 jsf 中模拟 HttpSession。

【问题讨论】:

    标签: unit-testing jsf junit mocking mockito


    【解决方案1】:

    1- 使用 FacesContextMocker 类:

    public abstract class FacesContextMocker extends FacesContext {
    
        private FacesContextMocker() {}
    
        private static final Release RELEASE = new Release();
    
        private static class Release implements Answer<Void> {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                setCurrentInstance(null);
                return null;
            }   
        }
    
        public static FacesContext mockFacesContext() {
            FacesContext context = Mockito.mock(FacesContext.class);
            setCurrentInstance(context);
            Mockito.doAnswer(RELEASE).when(context).release();
            return context;
       }
    }
    

    2- 在测试类的@Before 方法中执行以下操作:

        FacesContextMocker.mockFacesContext();
    
        ExternalContext externalContext = Mockito.mock(ExternalContext.class);
        Mockito.when(FacesContext.getCurrentInstance().getExternalContext())
                .thenReturn(externalContext);
    
        HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
        Mockito.when(
                FacesContext.getCurrentInstance().getExternalContext()
                        .getRequest()).thenReturn(request);
    
        HttpSession httpSession = Mockito.mock(HttpSession.class);
        Mockito.when(GeneralUtils.getHttpSession()).thenReturn(httpSession);
    

    3-getHttpSession方法如下:

       public static HttpSession getHttpSession() {
    
        return ((HttpServletRequest) FacesContext.getCurrentInstance()
                .getExternalContext().getRequest()).getSession();
    }
    

    4- 在测试方法中执行以下操作:

    Mockito.when(
                    GeneralUtils.getHttpSession().getAttribute(
                            "userID")).thenReturn("1");
    

    5- 这是假设在您正在为您进行单元测试的服务方法中具有如下代码:

    String currentUserID = (String) GeneralUtils.getHttpSession()
                        .getAttribute(userID);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-15
      • 2013-12-20
      • 1970-01-01
      • 2012-06-01
      • 1970-01-01
      相关资源
      最近更新 更多