1

I have 'MyClass' inheriting from 'BaseClass' with a method doBaseStuff() that isn't overloaded:

public class BaseClass {
    public String doBaseStuff(String var1, String var2) {
        //Do something
        return someStringValue;
    }

public class MyClass extends BaseClass {
    public String doMyStuff(String var1, String var2) {
        //Do some stuffs
        doBaseStuff(var1, var2);
        //Do more stuffs
        return someStringValue;
    }
}

Then I have a test case for MyClass:

@RunWith(MockitoJUnitRunner.class)
public class MyClassTest {

    @InjectMocks
    MyClass myClass;

    public void testDoOtherThing() {
        // Some setups
        when(myClass.doBaseStuff(dummyVar1, dummyVar2))
                .thenReturn("This isn't catching the invocation!");

        myClass.doMyStuff(dummyVar1, dummyVar2);

        // Some verify statements
    }
}

However, when/then statement for doBaseStuff() is not mocking the behaviour whenever that method is invoked.

As a (very shitty) workaround, I can declare a separate BaseClass object as a member of MyClass:

public class MyClass extends BaseClass {
    private Baseclass baseClass;

    ...

         baseClass.doBaseStuff(var1, var2);

    ...

}

public class MyClassTest {
    @InjectMocks
    MyClass myClass;
    @Mock
    BaseClass baseClass;

    ...

    when(baseClass.doBaseStuff(dummyVar1, dummyVar2))
            .thenReturn("This technically works, but ugh...");

    ...

}

However, MyClass one of the subclasses of BaseClass shares common functionality.

Is there any way for MyClass mock to be aware of doBaseStuff() implementation?

Caladbolgll
  • 400
  • 1
  • 3
  • 15
  • Possible duplicate of [How to mock super class method using Mockito or anyother relavent java framework](https://stackoverflow.com/questions/30319580/how-to-mock-super-class-method-using-mockito-or-anyother-relavent-java-framework) – Guillaume F. Apr 18 '19 at 21:43
  • 1
    `myClass` is not a mock, so you can't stub its methods. https://static.javadoc.io/org.mockito/mockito-core/2.27.0/index.html?org/mockito/Spy.html – JB Nizet Apr 18 '19 at 21:49

1 Answers1

1

You want to use @Spy instead:

@Spy
MyClass myClass;

The difference between a mock and a spy is well answered here.

Also, when().thenReturn() method will acually execute the real method. Only the return value is substituted. If you don't want to execute the original method, use doReturn().when() syntax instead:

doReturn("This technically works, but ugh...").when(myClass).doBaseStuff(dummyVar1, dummyVar2);
Pavel Smirnov
  • 4,611
  • 3
  • 18
  • 28