> For the complete documentation index, see [llms.txt](https://notes.tejpratapsingh.com/_/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://notes.tejpratapsingh.com/_/java-testing/powermockito/powermockito.stub.md).

# PowerMockito.stub()

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

```java
// 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()`.

```java
@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`.
