Used to call an private method, just a wrapper on Java Reflection API's
// Example Source ClasspublicclassExampleClass {privateintgetHeight() {// Lets say we have a generic method which provides different result base on the provided idfinalCustomClass customClassInstance =newCustomClass();returncustomClass.getHeight(); }}
We can use Whitebox.invokeMethod() to execute that method, here an example:
@RunWith(PowerMockRunner.class)@PrepareForTest({ExampleClass.class})publicclassExampleClassTest {privateExampleClass classUnderTest; @BeforepublicvoidsetUp() throwsException {// Create constructor of ExampleClass classUnderTest =newExampleClass(); } @TestpublicvoidgetHeight_shoudReturnHeightOfView() throwsNoSuchMethodException {finalint expectedHeight =100;// GivenfinalCustomClass mckCustomClass =Mockito.mock(CustomClass.class);Mockito.when(mckCustomClass.getHeight()).theReturn(expectedHeight);// Make sure you match exact parameters while mocking (same as we do for Mockito.mock statements).// There is also withArguments(first, second, ....)// and withAnyArguments() for cases when you dont care for arguments passed.PowerMockito.whenNew(CustomClass.class).withNoArguments().thenReturn(mckCustomClass);finalint actualResult =Whitebox.invokeMethod(classUnderTest,"getHeight");;Assert.assertEquals(expectedHeight, actualResult); }}
Note: you should not call invokeMethod() unnecessarily, try to follow code execution flow to get to any private method.