セッション属性を取得するサービス メソッドがあり、このサービス メソッドの単体テストを行いたいのですが、jsf で HttpSession をモックする方法を知りたいと思っていました。
2487 次
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 に答える