GhostJumper
GhostJumper

Reputation: 111

counting times private method is called with PowerMockito

I'm trying to get the number of times a private method has been called. I can do this with mockito for public methods:

Mockito.verify(mockedObject, times(numberOfTimes)).methodToBeChecked();

Is there an equivalent for PowerMockito? I dont want tu use spy.

Thanks in advance.

Upvotes: 0

Views: 765

Answers (1)

Renato
Renato

Reputation: 2157

Yes, it is.

Here my dependencies:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.28.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito2</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>2.0.2</version>
    <scope>test</scope>
</dependency>

The class under test:

public class A {


    private void _test(){

    }

    public void test(){
        for (int i = 0; i < 10; i++) {
            _test();
        }
    }
}

My Junit:

@RunWith(PowerMockRunner.class)
@PrepareForTest({A.class})
public class ATest {

    private A a;

    public ATest() {
    }

    @Before
    public void setUp() {
        a = PowerMockito.spy(new A());

    }

    /**
     * Test of test method, of class A.
     */
    @Test
    public void testTest() throws Exception {
        a.test();
        PowerMockito.verifyPrivate(a, Mockito.times(10)).invoke("_test");
    }

}

But using powermockito has drawbacks:

  1. you cannot monitor coverage with tool as Jacoco and on the fly instrumentation
  2. probably you are developing an hard to test design: you should use it only if you are working to a legacy and impossible to change code

Upvotes: 2

Related Questions