Search code examples
javarecursionstatic-methodspowermockito

Issue with PowerMockito verifyStatic() method for a static recursive function in Java


I am new to Mockito and PowerMockito. I have a test method where I use PowerMockito to mock a static recursive method. I need to verify that particular method is invoked 2 times, but the test case fails. Also the actual method is not hit.

This is the code.

Testing method:

public class Util {

  public static void methodToTest(String a, String b) {
       ..............

       methodToTest(c, d);
  }
}

Test case :

public void testMethodToTest() {
     PowerMockito.mockStatic(Util.class);
     Util.methodToTest(e, f);

     verifyStatic(Util.class, Mockito.times(2));
     Util.methodToTest(Matchers.anyString(), Matchers.anyString());
}

But when I run the test it fails with the following error.

Wanted 2 times but was 1 time.

    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:182)
    at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:164)
    at org.powermock.core.MockGateway.methodCall(MockGateway.java:141)

Ideally with Util.methodToTest(e, f) call,it should call the actual methodToTest twice.

I debugged the code and then I noticed that Util.methodToTest(e, f) call does not go inside the actual method.

What is the issue in this code? How can I verify that this recursive method is getting called twice?

Powermock version - 1.7.4


Solution

  • The problem here is that you are invoking intercepted method from inside of spied/mocked object. Interception is made when call is made from the outside. So original call is "registered" but not the internal one.

    I am not sure it is a bug or expected behavior, but I have ran into the same issue some time ago (but not with statics) and If I recall I redesigned the test.