Notes
Java Testing
Java Testing
  • Java Testing
  • Mockito
    • Mockito.mock()
    • Mockito.spy()
    • Mockito.verify()
    • Mockito.mockStatic()
    • ArgumentMatcher
    • ArgumentCaptor
  • PowerMockito
    • Why we need PowerMock?
    • PowerMockRunner
    • PrepareForTest
      • Understanding @PrepareForTest
    • SuppressStaticInitializationFor
    • PowerMockito.suppress()
    • PowerMockito.stub()
    • PowerMockito.replace()
    • PowerMockito.whenNew()
      • Limitation of PowerMockito.whenNew()
    • Whitebox.invokeMethod()
    • Whitebox.setInternalState()
    • Whitebox.getInternalState()
  • Tips
    • How to test ViewModel and LiveData
Powered by GitBook
On this page
  1. PowerMockito

PowerMockito.stub()

suppress() works best for void methods or constructors, but what if need to return something. For that we have stub().

// Example Source Class
public class ExampleClass extends CustomLibClass {
    public int someMethod() {
        final int valueFromSuper = super.someMethodThatOnlyWorksOnRumtime();
        return valueFromSuper * 2;
    }
}

Here, we have a method with that return something, and to test our method we need get a fixed value from CustomLibClass.someMethodThatOnlyWorksOnRumtime(). To achive that, we can use stub().

@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 someMethod_shouldReturnFour_whenCustomLibSomeMethodThatOnlyWorksOnRumtimeReturnTwo() throws NoSuchMethodException {
        // Given
        PowerMockito.stub(CustomLibClass.class.getDeclaredMethod("someMethodThatOnlyWorksOnRumtime")).toReturn(2);

        // When
        final int actualResult = classUnderTest.someMethod();

        // Then
        // As we stubbed someMethodThatOnlyWorksOnRumtime() to return 2, our result will be 2 * 2 = 4
        Assert.assertEquals(4, actualResult);
    }
}

Note: keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of stub method, we need to add ExampleClass.class in @PrepareForTest.

PreviousPowerMockito.suppress()NextPowerMockito.replace()

Last updated 1 year ago