'PowerMock expectNew creating real objects and won't return mocked instance

I'm working with PowerMock to return the mock object of a private method but It never mocks the constructor define in private method and just proceeds as if it were normal.

Class Util {
   public void getData() {
      DirContext context = this.getContext();  //Private Method
   }

   private DirContext getContext() {
      final Hashtable<String, String> hashObj = new Hashtable<>();
      hashObj.put("java.naming.factory.initial","CONTEXT_FACTORY_VALUE");
      ......
      ......
      ......


      
      return new InitialDirContext(hashObj);  
   }
}

Test Class

@RunWith(PowerMockRunner.class)
@PrepareForTest({Util.class,InitialDirContext.class})
public class UtilTest {
   private Util utilMock;
  
   @Before
    public void setUp() {
        this.utilMock = new Util();
    }
   
   @Test
    public void getDataTest() throws Exception {
        final Hashtable<String,String> hashMock = mock(Hashtable.class);

        InitialDirContext cntxMock = PowerMock.createMock(InitialDirContext.class);     
        PowerMock.expectNew(InitialDirContext.class, hashMock).andReturn(cntxMock); //not returing the mock data

        this.utilMock.getData();
   }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source