Why is PowerMockito throwing TooManyActualInvocations?

Viewed 73

I'm trying to use Mockito and PowerMockito to verify that a private method is being called and it's working properly. The point is that there's method that when spying the class with PowerMockito, it throws an exception

I don't know why if I run the test spying the object with PowerMockito, it's telling me that the method is being called 3 times instead of 1 (I put some logs and it's being called just once). But if spy the object with mockito, it's working properly, (obviously commenting the verifyPrivate part)

This woul be the stack trace:

org.mockito.exceptions.verification.TooManyActualInvocations: 
myObject.publicMethod2();
Wanted 1 time:
-> at com.example.myPackage.publicMethod2(MyClass.kt:530)
But was 3 times:
-> at com.example.myPackage.publicMethod1(MyClass.kt:172)
-> at com.example.myPackage.publicMethod2(MyClass.kt:530)
-> at com.example.myPackage.publicMethod2(MyClass.kt:530)

The code looks something like this:

@RunWith(PowerMockRunner::class)
@PrepareForTest(MyClass::class)
class myObjectTest {

      @Test
      fun myTest(){
        val myObject = MyClass()
        //val myObjectSpy = spy(myObject)
        val myObjectSpy  = PowerMockito.spy(myObject)
    
        myObjectSpy.publicMethod1()
        verify(myObjectSpy).publicMethod2()
        verifyPrivate(myObjectSpy).invoke("myPrivateMethod3");
      }
    
    }

This is the code I'm trying to test

  override fun publicMethod1() {
    publicMethod2()
    myPrivateMethod3()
  }

These are my dependencies in my gradle file:

  testImplementation 'org.powermock:powermock-api-mockito2:2.0.9'
  testImplementation 'org.mockito:mockito-core:2.8.9'
  testImplementation "org.powermock:powermock-module-junit4:2.0.9"
  testImplementation "org.powermock:powermock-core:2.0.9"

I've revise if there is any problem with the decencies and look for other posts but I'm unable to detect where's the problem.

0 Answers
Related