无法使用 PowerMock 模拟构造函数

Not able to mock constructor using PowerMock

在下面的代码中,我无法使用 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();

通过这样做,您告诉编译器 return 一个模拟实例 apspPortletRequestMock 每当 'new' 运算符在 class APSPPortletRequest 上调用时,任何请求对象 class 作为参数.

而且您还遗漏了一个小问题,您也需要重播所有 Easymock 对象。即 EasyMock.replay(...); 也需要存在。

希望对您有所帮助!

祝你好运!

如果你想模拟下面的方法:

EncryptionHelper encryptionhelper = new EncryptionHelper("cep", true);

你可以通过这种方式使用powerMock。

1。导入 类.

导入静态org.powermock.api.support.membermodification.MemberMatcher.method;

导入静态org.powermock.api.support.membermodification.MemberModifier.stub;

2。在你的junit test calss.

上面添加注解@RunWith和@PrepareForTest

@RunWith(PowerMockRunner.class)

@PrepareForTest({ EncryptionHelper.class})

3.Mock吧。

EncryptionHelper encryptionHelperMock = PowerMock.createMock(EncryptionHelper.class);

PowerMock.expectNew(EncryptionHelper.class, isA(String.class), EasyMock.anyBoolean()).andReturn(encryptionHelperMock);

4.Reply这

PowerMock.replayAll(encryptionHelperMock);

我按照上面的步骤做了,效果很好。