EasyMock: cut constructor call in java

I have similar questions on this board, but none of them answer my question. It sounds strange, but is it possible to scoff at calling a constructor on an object that you are mocking.

Example:

class RealGuy { .... public void someMethod(Customer customer) { Customer customer = new Customer(145); } } class MyUnitTest() { public Customer customerMock = createMock(Customer.class) public void test1() { //i can inject the mock object, but it still calling the constuctor realGuyobj.someMethod(customerMock); //the constructor call for constructor makes database connections, and such. } } 

How can I expect a constructor call? I can change the call to the Customer constructor to use newInstance, but I'm not sure if this will help. I cannot control what the body of the new Customer(145) constructor does.

Is it possible?

+7
source share
3 answers

You can do this with EasyMock 3.0 and above.

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

You cannot do this with easymock, as it does not support mocking constructors. There is a library called powermock that can do this and is the only mocking library, as far as I know, that can block constructors and static methods in Java.

+11
source
 import static org.powermock.api.easymock.PowerMock.expectNew; instance = new UsesNewToInstantiateClass(); expectNew(AnyOldClass.class).andReturn(anyClass); 
+1
source

All Articles