Not able to mock constructor using PowerMock

北城以北 提交于 2019-12-11 09:23:31

问题


Here in below code i am not able to Mock Constructor using PowerMock. I want to MOck below statement.

APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);

below are my mocking steps

@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();
   }
}

Please suggest me on That.


回答1:


as you want to mock this line

APSPPortletRequest wrappedRequest = new APSPPortletRequest(request);

this object creation call takes only one parameter,but while mocking in your test method you are passing two values to expectNew method.

actually you should be doing

PowerMock.expectNew(APSPPortletRequest.class, EasyMock.anyObject(requestClass.class)).andReturn(apspPortletRequestMock).anyTimes();

by doing this you are telling compiler to return a mocked instance apspPortletRequestMock whenever 'new' operator is called on class APSPPortletRequest with any object of request class as parameter.

and you are also missing a small point you need to replay all the Easymock objects too.. i.e. EasyMock.replay(...); also needs to be present.

hope this helps!

Good luck!




回答2:


If you want to mock below method:

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

You can do it with powerMock in this way.

1. import classes.

import static org.powermock.api.support.membermodification.MemberMatcher.method;

import static org.powermock.api.support.membermodification.MemberModifier.stub;

2. add Annotation @RunWith and @PrepareForTest above you junit test calss.

@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);

I do it with above steps and work fine.



来源:https://stackoverflow.com/questions/29818830/not-able-to-mock-constructor-using-powermock

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!