PowerMockito.whenNew()
// Example Source Class
public class ExampleClass {
public int getHeight() {
// Lets say we have a generic method which provides different result base on the provided id
final CustomClass customClassInstance = new CustomClass();
return customClass.getHeight();
}
}@RunWith(PowerMockRunner.class)
@PrepareForTest({
ExampleClass.class
})
public class ExampleClassTest {
private ExampleClass classUnderTest;
@Before
public void setUp() throws Exception {
// Create constructor of ExampleClass
classUnderTest = new ExampleClass();
}
@Test
public void getHeight_shoudReturnHeightOfView() throws NoSuchMethodException {
final int expectedHeight = 100;
// Given
final CustomClass 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 don't care for arguments passed.
PowerMockito.whenNew(CustomClass.class).withNoArguments().thenReturn(mckCustomClass);
final int actualResult = classUnderTest.getHeight();
Assert.assertEquals(expectedHeight, actualResult);
}
}Last updated