java – 即使私有方法被模拟,PowerMock也会抱怨参数不正确

我正在尝试使用PowerMock,我正在尝试模拟这样的私有方法:

expectPrivate(n, "doLogin", anyString(), anyString()).andReturn(true);

也就是说,无论传递的参数如何,我都希望从doLogin返回true.
委托给这个私有方法的公共方法只是传递参数.以下是要模拟的类的定义:

class N {
        public boolean login(String username, String password) {
            return doLogin(username, password);
        }
        private boolean doLogin(String u, String p){
            //validate login
            //...
            //...
            return true;
        }
     }

这是我试图调用mock的测试类:

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)

因此,当特定的字符串传递给public login()方法时,模拟框架并不高兴,但是当使用anyString时很好.理想情况下,我希望由于私有doLogin的调用被嘲笑,所以不应该这样.
我错过了什么?

最佳答案 我有一个类似的问题,我认为你的问题可以在param传递给PowerMock expectPrivate方法的Matchers anyString()中.

基于您的导入,您使用的是Mockito Matchers而不是EasyMock Matchers:org.mockito.Matchers.anyString.

您可以尝试更改下一个的Matchers:EasyMock.anyString()

import org.easymock.EasyMock;

...

expectPrivate(n, "doLogin", EasyMock.anyString(), EasyMock.anyString()).andReturn(expected);

希望能帮助到你.

点赞