nik
nik

Reputation: 210

Not able to mock constructor using PowerMock

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.

Upvotes: 1

Views: 1743

Answers (2)

Vihar
Vihar

Reputation: 3831

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!

Upvotes: 1

chendu
chendu

Reputation: 584

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.

Upvotes: 0

Related Questions