1

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

4

1 回答 1

3

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);
于 2013-11-02T22:28:51.223 回答