Question

PowerMock provides the method expectPrivate to mock out private methods, however it appears only in EasyMock api and not the Mockito API.

So, is there an equivalent for PowerMockito? I'm guessing not because I haven't found it and because of this wiki entry. but that doesn't actually prevent PowerMockito from working around it. So, I'm asking this mostly for confirmation and since I think this will be of value for others.

Was it helpful?

Solution

PowerMockito provides ways to mock private methods as well, from the API:

<T> WithOrWithoutExpectedArguments<T> when(Object instance, Method method) 
Expect calls to private methods.


verifyPrivate(Object object, org.mockito.verification.VerificationMode verificationMode) 
      Verify a private method invocation with a given verification mode.

There are a bunch of other signatures of the type described above.

An example:

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Matchers.eq;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Foo.class)
public class SimpleTest {

    @Test
    public void testHello() throws Exception {
        Foo foo = PowerMockito.spy(new Foo());
        foo.sayHello();
        PowerMockito.verifyPrivate(foo).invoke("hello", eq("User"));
    }
}

class Foo {
    public void sayHello() {
        System.out.println(hello("User"));
    }

    private String hello(String user) {
        return "Hello " + user;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top