How to mock InitialContext constructor in unit testing
<p>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>

<pre><code>private void someMethod(int id1, int id2, HashMap map){
    ......some code........

    Context ctx = new InitialContext();
    Object ref = ctx.lookup("com.java.ejbs.MyEJB");

    EJBHome ejbHome = (EJBHome)PortableRemoteObject.narrow(ref, EJBHome.class);
    EJBBean ejbBean = (EJBBean)PortableRemoteObject.narrow(ejbHome.create(), EJBBean.class);
    ejbBean.someMethod(id1,name);

    .......some code.......}
</code></pre>

<p>My unit test for above method</p>

<pre><code>@Test
public void testsomeMethod() throws Exception {

    .......setting initial code...
    //Mock context and JNDI

    InitialContext cntxMock = PowerMock.createMock(InitialContext.class);
    PowerMock.expectNew(InitialContext.class).andReturn(cntxMock);
    expect(cntxMock.lookup("com.java.ejbs.MyEJB")).andReturn(refMock);               

    ..........some code..........

    PowerMock.replayAll();
    Whitebox.invokeMethod(ObjectOfsomeMethodClass, "someMethod", id1, id2, map);


}
</code></pre>

<p>when the <strong>Whitebox.invokeMethod(ObjectOfsomeMethodClass, "someMethod", id1, id2, map)</strong> method invokes it gives following exception.</p>

<pre><code>javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
</code></pre>

<p>I believe, although we mock the <strong>Context</strong> in test method, it does not use the mock object when calling <strong>Whitebox.invokeMethod(ObjectOfsomeMethodClass, "someMethod", id1, id2, map)</strong> method, instead  of that its trying to invoke the <strong>Context ctx = new InitialContext();</strong> method in original method(someMethod).</p>