EasyMock: Mock out a constructor call in java

情到浓时终转凉″ 提交于 2019-12-01 03:54:39

you can do so with EasyMock 3.0 and above.

Customer cust = createMockBuilder(Customer.class)
     .withConstructor(int.class)
     .withArgs(145)
     .addMockedMethod("someMethod")
     .createMock();

You can't do this with easymock, as it doesn't support mocking constructors. There's a library called powermock which can do that and is the only mocking library, as far as I know, that can stub constructors and static methods in Java.

import static org.powermock.api.easymock.PowerMock.expectNew;

instance = new UsesNewToInstantiateClass();
expectNew(AnyOldClass.class).andReturn(anyClass);

And this is why you want to inject your dependencies (via Guice or similar package) instead of creating them inside your class.

Then you don't HAVE TO mock their construction.

This assumes (a) that this is your code that you can change, and (b) that the objects in question are complex enough that you should inject them. Constructing simple objects inside your class are fine, but then you shouldn't need to mock them.

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