Search code examples
javapowermockito

Verify private static method on final class gets called using PowerMockito


I have the following class

public final class Foo {
  private Foo() {}
  public static void bar() {
    if(baz("a", "b", new Object())) { }
  }
  private static boolean baz(Object... args) {
    return true;  // slightly abbreviated logic
  }
}

And this is my Test:

@PrepareOnlyThisForTest(Foo.class)
@RunWith(PowerMockRunner.class)
public class FooTest {
  @Test
  public void bar() {
    PowerMockito.mockStatic(Foo.class); // prepare
    Foo.bar(); // execute
    verifyPrivate(Foo.class, times(1)).invoke("baz", anyVararg()); // verify - fails
  }
}

For that, I get the following error message - and I don't understand why...

Wanted but not invoked com.example.Foo.baz( null );

However, there were other interactions with this mock.

Removing the prepare line above seems to make the verify line pass no matter for how many times you check for... :(

(Our SONAR code checks enforce that each test has some sort of assertXyz() in it (hence the call to verify()) and enforces a very high test coverage.)

Any ideas how to do this?


Solution

  • The problem with your code is that you mock Foo so your method implementations won't be called by default such that when you call Foo.call() it does nothing by default which means that it never avtually calls baz that is why you get this behavior. If you want to partially mock Foo, mock it using the option Mockito.CALLS_REAL_METHODS in order to make it call the real methods as you seem to expect, so the code should be:

    @PrepareOnlyThisForTest(Foo.class)
    @RunWith(PowerMockRunner.class)
    public class FooTest {
        @Test
        public void bar() throws Exception {
            PowerMockito.mockStatic(Foo.class, Mockito.CALLS_REAL_METHODS); // prepare
            ...
        }
    }