在下面的代码中,我无法使用PowerMock模拟构造函数。 我想在MOV下面发表声明。
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();
}
}
请建议我。
答案 0 :(得分:1)
因为你想模仿这一行
APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);
此对象创建调用只接受一个参数,但在测试方法中进行模拟时,您将两个值传递给expectNew
方法。
PowerMock.expectNew(APSPPortletRequest.class, EasyMock.anyObject(requestClass.class)).andReturn(apspPortletRequestMock).anyTimes();
通过这样做,你告诉编译器只要' new'就会返回一个模拟的实例apspPortletRequestMock。在类APSPPortletRequest上调用operator,并将任何请求类对象作为参数。
你也错过了一个小点,你需要重播所有的Easymock对象......即EasyMock.replay(...);
也需要存在。
希望这有帮助!
祝你好运!答案 1 :(得分:0)
如果你想模仿以下方法:
EncryptionHelper encryptionhelper = 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。在junit test calss上方添加注释@RunWith和@PrepareForTest。
@RunWith(PowerMockRunner.class)
@PrepareForTest({EncryptionHelper.class})
3.Mock it。
EncryptionHelper encryptionHelperMock = PowerMock.createMock(EncryptionHelper.class);
PowerMock.expectNew(EncryptionHelper.class,isA(String.class),EasyMock.anyBoolean())。andReturn(encryptionHelperMock);
4.Reply it
PowerMock.replayAll(encryptionHelperMock);
我按照上述步骤进行操作并正常工作。