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})publicclassExampleClassTest {privateExampleClass classUnderTest; @BeforepublicvoidsetUp() throwsException {// Create constructor of ExampleClass classUnderTest =newExampleClass(); } @Test public void someMethod_shouldReturnFour_whenCustomLibSomeMethodThatOnlyWorksOnRumtimeReturnTwo() throws NoSuchMethodException {
// Given PowerMockito.stub(CustomLibClass.class.getDeclaredMethod("someMethodThatOnlyWorksOnRumtime")).toReturn(2);// Whenfinalint 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.