Skip to content Skip to sidebar Skip to footer

Mockito Spy - When Calling Inner Class Method Not Spying Method In Spy Object

I have class with inner class as following: public class ClassWithInnerObject { private final InnerObject innerObject; public ClassWithInnerObject() { innerObject = new I

Solution 1:

What is wrong?

Well, the problem here is quite subtle, when you call Mockito.spy(p), mockito creates behind the scene some kind of decorator over your instance of ClassWithInnerObject allowing to monitor all methods calls on your instance. Thanks to that, you can check how many times a given method has been called but on the decorator only not on your instance. And here, when you use an inner class, it calls innerFunc() on your instance of ClassWithInnerObject not on the decorator so for MockitoinnerFunc()has not been called.

Solution 2:

You can Fix that by using "ClassWithInnerObject.this." in inner class.

publicclassInnerObject {
  publicvoidouterFunc() {
    ClassWithInnerObject.this.innerFunc();
  }
}

Post a Comment for "Mockito Spy - When Calling Inner Class Method Not Spying Method In Spy Object"