是否可以在Arquillian测试中注入FacesContext?或者更好的方法是嘲笑它?网络上的最后几年我找不到任何例子。 FacesContext为null。
@Category(Arquillian.class)
@RunWith(Arquillian.class)
public class ControllerIT extends ArquillianDeployementsIT {
@Inject
private Controller controller;
@Test
public void shouldInitialize() {
controller.getStatistics();
}
@ManagedBean
@ViewScoped
public class Controller {
public void getStatistcs(
FacesContext context = FacesContext.getCurrentInstance();
}
}
谢谢和问候
答案 0 :(得分:1)
最后我解决了这样的问题,也许对某人有帮助。
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import javax.faces.application.Application;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.servlet.http.HttpServletRequest;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public abstract class ContextMocker extends FacesContext {
private static final Release RELEASE = new Release();
private ContextMocker() {
}
public static FacesContext mockServletRequest() {
FacesContext context = mock(FacesContext.class);
setCurrentInstance(context);
Mockito.doAnswer(RELEASE)
.when(context)
.release();
Map<String, Object> session = new HashMap<>();
ExternalContext ext = mock(ExternalContext.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(ext.getSessionMap()).thenReturn(session);
when(context.getExternalContext()).thenReturn(ext);
when(ext.getRequest()).thenReturn(request);
when(ext.isUserInRole(anyString())).thenReturn(true);
return context;
}
private static class Release implements Answer<Void> {
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
setCurrentInstance(null);
return null;
}
}
}
并且在测试中:
@Category(Arquillian.class)
@RunWith(Arquillian.class)
public class LoginControllerIT extends ArquillianWebIT {
@Inject
private LoginController loginController;
private FacesContext facesContext;
@Before
public void init() {
facesContext = ContextMocker.mockServletRequest();
}
@After
public void release() {
facesContext.release();
}
@Test...