Problem to mock constructor

1,061 views
Skip to first unread message

Gustavo Silva

unread,
Jan 30, 2018, 2:44:32 PM1/30/18
to PowerMock
I'm having problem to mock a constructor without parameters while mantaing the constructor with paremeters working as before.


The following is working as expected to me:

Date mockedDate = new Date(1517229382542L);

PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(mockedDate);

System.out.println("without arguments: " + new Date());


But when i try to call the Date constructor with arguments like this:

Date mockedDate = new Date(1517229382542L);

PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(mockedDate);

System.out.println("with arguments: " + new Date(1L));
System.out.println("without arguments: " + new Date());

The constructor with arguments return null.


If i try to mock both constructors like this:

Date mockedDate = new Date(1517229382542L);

PowerMockito.whenNew(Date.class).withArguments(Mockito.anyLong()).thenCallRealMethod();
PowerMockito.whenNew(Date.class).withNoArguments().thenReturn(mockedDate);

System.out.println("with arguments: " + new Date(1L));
System.out.println("without arguments: " + new Date());


I get the following error:

org.mockito.exceptions.base.MockitoException:
Cannot call abstract real method on java object!
Calling real methods is only possible when mocking non abstract method.
  //correct example:
  when(mockOfConcreteClass.nonAbstractMethod()).thenCallRealMethod();




Can someone help me?

Thanks,

Gustavo Paiva.






Gustavo Silva

unread,
Jan 30, 2018, 9:18:51 PM1/30/18
to PowerMock
I've found a way around, don't know if this is the best way but it worked.
i've started to user the thenAnswer method and made a special vaue to return the mocked value when the constructor with no argument is called. The case when the constructor get this special value is the case where i should have mocked and return a specfic date, otherwhise i just create a spy and return a date witht the specified time.

PowerMockito.whenNew(Date.class).withNoArguments().thenAnswer(inv -> new Date(-1L));
PowerMockito.whenNew(Date.class).withArguments(Mockito.anyLong()).thenAnswer(inv -> {
Long argument = inv.getArgumentAt(0, Long.class);

if (argument == -1L) {
argument = 1517229382542L;
}

Date date = Mockito.spy(Date.class);
date.setTime(argument);
return date;
});
Reply all
Reply to author
Forward
0 new messages