1

Using PowerMockito to setup a test containing a private method ala this.

Class:

public class SomeMod {
    public void somefunc() {
        Logger.debug("somefunc");
        ...
        privFunction(param);
        ...
    }

    private void privFunction(param) {
        Logger.debug("privFunction");
    }
}

Test:

@RunWith(PowerMockRunner.class)
@PrepareForTest({SomeMod.class})
public class somemod_test {
    ...
    @Test public void test0() {
        SomeMod_spy somemod = spy(new SomeMod());
        PowerMockito.when(somemod, "privFunction", "param").thenReturn(someMockedValue);

        ...
        somemod.somefunc();
    }

}

When I run this and set breakpoints on both Logger.debug statements Im seeing the privFunction get hit before the somefunc. If I comment out the call to somemod.somefunc() in the test, the privFunction is still getting hit.

What am I doing wrong?


Edit:

I used PowerMockito.when().thenReturn() instead of the recommeded PowerMockito.doReturn().when() syntax as the former throws NPE and UnfinishedStubbingException. This suggests that my test environment isn't setup properly. Not sure where to look to fix this.

ethrbunny
  • 10,379
  • 9
  • 69
  • 131
  • Answered here https://stackoverflow.com/questions/14651138/powermock-mock-a-static-method-then-call-real-methods-on-all-other-statics – Aykut Akıncı Apr 11 '19 at 09:18

2 Answers2

3

After taking a short walk and then a fresh look at the code the problem / answer is the linkage of the mock/spy calls to setup the doReturn.

Instead of:

spy(new SomeMod())

Use:

PowerMockito.spy(new SomeMod())

This will setup the test(s) according to the docs.

ethrbunny
  • 10,379
  • 9
  • 69
  • 131
2

You have to use the doReturn().when() syntax to keep the mocked method from being called. It's the only way I know of to do it.

Jim Barrows
  • 3,634
  • 1
  • 25
  • 36