gpt4 book ai didi

java - Mockito session 设置属性空指针异常

转载 作者:太空宇宙 更新时间:2023-11-04 12:54:17 35 4
gpt4 key购买 nike

我正在尝试设置 session 进行测试,但收到 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();
}
}

我做错了什么 - 设置 session 的正确方法是什么?

最佳答案

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 或其他测试覆盖技术进行模拟。

关于java - Mockito session 设置属性空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35537601/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com