我正在尝试powermock,并试图模拟这样的私人方法:
expectPrivate(n, "doLogin", anyString(), anyString()).andReturn(true);
也就是说,我希望true
从doLogin
返回,而与传递的参数无关。委派该私人方法的公共方法只需通过参数即可。这是要嘲笑的类的定义:
class N {
public boolean login(String username, String password) {
return doLogin(username, password);
}
private boolean doLogin(String u, String p){
//validate login
//...
//...
return true;
}
}
这是我试图调用模拟的测试类:
import static org.junit.Assert.assertEquals;
import static org.powermock.api.easymock.PowerMock.createPartialMock;
import static org.powermock.api.easymock.PowerMock.expectPrivate;
import static org.powermock.api.easymock.PowerMock.replay;
import static org.powermock.api.easymock.PowerMock.verify;
import static org.mockito.Matchers.anyString;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
@RunWith(PowerMockRunner.class)
@PrepareForTest(N.class)
public class NodeAccessorTest {
private String username = "admin";
private String password = "asdf";
@Test
public void testMockLogin() throws Exception {
N n = createPartialMock(N.class,
"doLogin", String.class, String.class);
boolean expected = true;
expectPrivate(n, "doLogin", anyString(), anyString()).andReturn(expected);
replay(n);
boolean actual = n.login("A", "B");
verify(n);
assertEquals("Expected and actual did not match", expected, actual);
}
}
这是故障跟踪:
java.lang.AssertionError:
Unexpected method call N.doLogin("A", "B"):
N.doLogin("", ""): expected: 1, actual: 0
at org.easymock.internal.MockInvocationHandler.invoke(MockInvocationHandler.java:44)
at org.powermock.api.easymock.internal.invocationcontrol.EasyMockMethodInvocationControl.invoke(EasyMockMethodInvocationControl.java:91)
at org.powermock.core.MockGateway.doMethodCall(MockGateway.java:124)
at org.powermock.core.MockGateway.methodCall(MockGateway.java:185)
at com.pugmarx.mock.N.doLogin(N.java)
at com.pugmarx.mock.N.login(N.java:60)
因此,当特定的String
S传递给public login()
方法时,模拟框架并不高兴,但是当使用anyString
时很好。理想情况下,我希望,由于嘲笑了private doLogin
的电话,因此情况并非如此。我想念什么?
我也有一个类似的问题,我认为您的问题可以在param传递给PowerMock expectPrivate
方法的Matchers anyString()
中。
基于您的导入,您使用的是Mockito
匹配器而是EasyMock
匹配器:org.mockito.Matchers.anyString
。
您可以尝试更改下一个匹配器:EasyMock.anyString()
import org.easymock.EasyMock;
...
expectPrivate(n, "doLogin", EasyMock.anyString(), EasyMock.anyString()).andReturn(expected);
希望它有帮助。