Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EasyMock: Mock out a constructor call in java

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?

like image 527
Setzer Avatar asked Oct 04 '11 19:10

Setzer


People also ask

How do you mock a constructor in JAVA?

0, we can now mock Java constructors with Mockito. This allows us to return a mock from every object construction for testing purposes. Similar to mocking static method calls with Mockito, we can define the scope of when to return a mock from a Java constructor for a particular Java class.

What is EasyMock in Junit?

EasyMock is a mocking framework, JAVA-based library that is used for effective unit testing of JAVA applications. EasyMock is used to mock interfaces so that a dummy functionality can be added to a mock interface that can be used in unit testing.


1 Answers

you can do so with EasyMock 3.0 and above.

Customer cust = createMockBuilder(Customer.class)
     .withConstructor(int.class)
     .withArgs(145)
     .addMockedMethod("someMethod")
     .createMock();
like image 72
betaboy00 Avatar answered Sep 22 '22 17:09

betaboy00