我试图模拟 FacesContext 并让它工作,但不知道这是否是最好的方法。我在做模拟时使用了 Mockito。
FacesContext mock = null;
final Map<Object, Object> attributes = new HashMap<Object, Object>();
public void mockFacesContext() {
if (mock == null) {
mock = Mockito.mock(FacesContext.class);
try {
Method m = FacesContext.class.getDeclaredMethod(
"setCurrentInstance", FacesContext.class);
m.setAccessible(true);
m.invoke(FacesContext.class, mock);
} catch (Exception e) {
e.printStackTrace();
}
Mockito.when(mock.getAttributes()).thenReturn(attributes);
ExternalContext ext = Mockito.mock(ExternalContext.class);
Mockito.when(ext.getSession(false)).thenReturn(
Mockito.mock(HttpSession.class));
Mockito.when(mock.getExternalContext()).thenReturn(ext);
UIViewRoot uiViewRoot = Mockito.mock(UIViewRoot.class);
Mockito.when(uiViewRoot.getViewId()).thenReturn("/test");
Mockito.when(uiViewRoot.getLocale()).thenReturn(new Locale("se"));
Mockito.when(mock.getViewRoot()).thenReturn(uiViewRoot);
Application application = Mockito.mock(Application.class);
Mockito.when(application.getSupportedLocales()).thenReturn(
Mockito.mock(Iterator.class));
Mockito.when(mock.getApplication()).thenReturn(application);
}
return mock;
}