在下面的代码中,我无法使用PowerMock模拟构造函数。我想在下面的声明中嘟囔一下。
APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);
以下是我的模拟步骤
@PrepareForTest({APSPPortletRequest.class})
@RunWith(PowerMockRunner.class)
public class ReminderPortletControllerTest {
private PortletRequest requestMock;
private APSPPortletRequest apspPortletRequestMock;
public void setUp() throws Exception {
requestMock = EasyMock.createNiceMock(PortletRequest.class);
apspPortletRequestMock = EasyMock.createNiceMock(APSPPortletRequest.class);
}
@Test
public void testExecuteMethod() throws Exception {
PowerMock.expectNew(APSPPortletRequest.class, requestMock).andReturn(apspPortletRequestMock).anyTimes();
EasyMock.replay(apspPortletRequestMock, requestMock);
PowerMock.replayAll();
}
}
请建议我。
因为你想模拟这一行
APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);
此对象创建调用仅接受一个参数,但是在测试方法中模拟时,您将两个值传递给expectNew
方法。
其实你应该做的
PowerMock.expectNew(APSPPortletRequest.class, EasyMock.anyObject(requestClass.class)).andReturn(apspPortletRequestMock).anyTimes();
通过这样做,您告诉编译器在类 APSPPortletRequest 上调用"new"运算符并将请求类的任何对象作为参数时返回一个模拟实例 apspPortletRequestMock。
而且您还缺少一个小点,您还需要重播所有 Easymock 对象.. 即 EasyMock.replay(...);
也需要在场。
希望这有帮助!
祝你好运!
如果你想模拟下面的方法:
EncryptionHelperencryptionhelper = new EncryptionHelper("cep", true);
你可以用这种方式用powerMock来做到这一点。
1. 导入类。
import static org.powermock.api.support.membermodification.MemberMatcher.method;
import static org.powermock.api.support.membermodification.MemberModifier.stub;
2.添加注释@RunWith,并在您的JUNIT测试小腿上方@PrepareForTest。
@RunWith(PowerMockRunner.class)
@PrepareForTest({ EncryptionHelper.class})
3.模拟它。
EncryptionHelperencryptionHelperMock = PowerMock.createMock(EncryptionHelper.class);
PowerMock.expectNew(EncryptionHelper.class, isA(String.class), EasyMock.anyBoolean()).andReturn(encryptionHelperMock);
4.回复
PowerMock.replayAll(encryptionHelperMock);
我按照上述步骤进行操作,工作正常。