我正在尝试设置测试会话,但我得到的是NullPointerException
。我尝试了几种方法,但没有成功。
class Test {
public void testOne() {
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(true);
session.setAttribute("test", someValue()); //session value is null
}
}
//This is my Unit Test which have one method giving exception.Why the session is giving null value....
Class TestUnitTest {
private TestUnit testUnit;
private ExternalContext externalContext;
private HttpServletRequest request;
private HttpSession httpSession;
@Before
public void init() {
testUnit = new TestUnit();
externalContext = Mockito.mock(ExternalContext.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext()).thenReturn(externalContext);
request = Mockito.mock(HttpServletRequest.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext().getRequest()).thenReturn(request);
httpSession = Mockito.mock(HttpSession.class);
Mockito.when((request.getSession())).thenReturn(httpSession);
//I am getting null pointer exception while implementing in this way
@Test
public void testvalueTest() {
testUnit.testOne(); //Null pointer exception
verify(httpSession).setAttribute("test", someValue());
}
//I am getting Wanted not Invoked while implementing in this way Wanted not Invoked
@Test
public void testvalueTest() {
verify(httpSession).setAttribute("test", someValue()); //Wanted not invoked
testUnit.testOne();
}
}
我做错了什么 - 设置会话的正确方法是什么?
答案 0 :(得分:0)
externalContext = Mockito.mock(ExternalContext.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext()).thenReturn(externalContext);
request = Mockito.mock(HttpServletRequest.class);
Mockito.when(FacesContext.getCurrentInstance().getExternalContext().getRequest()).thenReturn(request);
Mockito通过覆盖实例方法来工作,并且不能覆盖静态方法。尽管PowerMock允许静态方法模拟,但您通常可以将对静态方法的调用重构为实例方法,然后使用Mockito或其他测试覆盖技术进行模拟。