PowerMock提供方法expectPrivate
来模拟私有方法,但它只出现在EasyMock api而不是Mockito API。
那么,是否有PowerMockito的等价物?我猜不是因为我没找到它而是因为this wiki entry。但这实际上并没有阻止PowerMockito解决它。所以,我要求这主要是为了确认,因为我认为这对其他人来说是有价值的。
答案 0 :(得分:4)
PowerMockito还提供了从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.
上面描述的类型有很多其他签名。
一个例子:
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;
}
}