【问题标题】:Mockito session set Attribute null pointer exceptionMockito 会话集属性空指针异常
【发布时间】:2016-02-21 14:51:22
【问题描述】:

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

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

【问题讨论】:

  • 我认为 MockitoAnnotations.initMocks(.class);不见了。

标签: java mockito junit4


【解决方案1】:
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 或其他测试覆盖技术进行模拟。

【讨论】:

    猜你喜欢
    • 2015-10-07
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2014-11-13
    • 1970-01-01
    • 2019-05-24
    • 2021-06-15
    • 1970-01-01
    相关资源
    最近更新 更多