Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Mockito equivalent way to expect constructor invocations like PowerMock.expectNew?

If it doesn't, does it exist on EasyMock?

Thanks.

like image 748
kaneda Avatar asked Sep 14 '11 13:09

kaneda


1 Answers

PowerMock is intended as an extension of both EasyMock and Mockito. From the horse's mouth: "PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities."

In any case, there is no EasyMock equivalent to expectNew and neither is there one in Mockito, either - that's exactly the hole that PowerMock is trying to fill. That being said, PowerMock is perfectly capable of doing this with Mockito. Here is the sample from the documentation:

How to mock construction of new objects

Use PowerMockito.whenNew, e.g.

whenNew(MyClass.class).withNoArguments().thenThrow(new
IOException("error message")); 

Note that you must prepare the class creating the new instance of MyClass for test, not the MyClass itself. E.g. if the class doing new MyClass() is called X then you'd have to do @PrepareForTest(X.class) in order for whenNew to work.

How to verify construction of new objects Use PowerMockito.verifyNew, e.g.

verifyNew(MyClass.class).withNoArguments();
like image 78
jhericks Avatar answered Sep 25 '22 20:09

jhericks