How to mock InitialContext constructor in unit testing

后端 未结 4 484
臣服心动
臣服心动 2020-12-06 03:16

when I try to mock following method(Method is using remote EJB call for business logic) for the Junit test, it gives javax.naming.NoInitialContextException

p         


        
4条回答
  •  忘掉有多难
    2020-12-06 03:32

    As of now (PowerMock 1.7.4)

    Create a mock using PowerMockito.mock(InitialContext.class) rather than PowerMockito.createMock(InitialContext.class)

    @Test
    public void connectTest() {
        String jndi = "jndi";
        InitialContext initialContextMock = PowerMockito.mock(InitialContext.class);
        ConnectionFactory connectionFactoryMock = PowerMockito.mock(ConnectionFactory.class);
    
        PowerMockito.whenNew(InitialContext.class).withNoArguments().thenReturn(initialContextMock);
        when(initialContextMock.lookup(jndi)).thenReturn(connectionFactoryMock);  
    
        ...
    
        // Your asserts go here ...
    }
    

    Do not create the InitialContext manually but let PowerMock do it for you. Also do not create a spy in which PowerMock expects an object. This means that you need to create the InitialContext instance.

提交回复
热议问题