EasyMock: Mock out a constructor call in java

Setzer picture Setzer · Oct 4, 2011 · Viewed 19.7k times · Source

I have a looked at similar questions on this board, but none of them answer my question. This sound strange, but is it possible to mock out a constructor call on the object you're 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's 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 Customer constructor call to use newInstance, but im not sure if that will help. I have no control over what the body of the new Customer(145) constructor does.

Is this possible?

Answer

betaboy00 picture betaboy00 · May 9, 2014

you can do so with EasyMock 3.0 and above.

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