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().

public class ExampleClassTest {

    private ExampleClass classUnderTest;

    public void setUp() throws Exception {
        // Create constructor of ExampleClass
        classUnderTest = new ExampleClass();

    public void someMethod_shouldReturnFour_whenCustomLibSomeMethodThatOnlyWorksOnRumtimeReturnTwo() throws NoSuchMethodException {
        // Given

        // 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.

Last updated