Search code examples
javajunitpowermockito

How to mock local variable in a static method of a private java class?


I am writing unit test for a static method 'updateStatusOfModel' in class 'Util' whose constructor is private.

This static method instantiates a local variable dbManager as follows:

ActivationDBManager dbManager = new ActivationDBManager();

This dbManager is used to call its method which I have to mock.

I have mocked this as follows but somehow, it is not working. Unit test is not picking the mock object for ActivationDBManager.

Any help is appreciated.

@Test 
@PrepareForTest(Util.class) 
void updateStatusModel() throws Exception {     
ActivationDBManager mockdbManager = Mockito.mock(ActivationDBManager.class); 
   PowerMockito.whenNew(ActivationDBManager.class).withNoArguments().thenReturn(mockdbManager);    

PowerMockito.doNothing().when(mockdbManager).updateDBStatus(Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyString());  

Util.updateStatus("", "", "", "");
}

Util.updateStatus is a static method.


Solution

  • You should add ActivationDBManager to @PrepareForTest, because you are manipulating its bytecode (using whenNew).