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?
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.
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.
you can do so with EasyMock 3.0 and above.
Customer cust = createMockBuilder(Customer.class)
.withConstructor(int.class)
.withArgs(145)
.addMockedMethod("someMethod")
.createMock();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With