我在这个板上看了类似的问题,但没有一个回答我的问题.这听起来很奇怪,但是可以在你正在嘲笑的对象上模拟一个构造函数调用.
例:
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. } }
我怎么能期待一个构造函数调用?我可以更改Customer构造函数调用以使用newInstance,但我不确定这是否有帮助.我无法控制新Customer(145)构造函数的主体.
这可能吗?
Customer cust = createMockBuilder(Customer.class) .withConstructor(int.class) .withArgs(145) .addMockedMethod("someMethod") .createMock();
翻译自:https://stackoverflow.com/questions/7653263/easymock-mock-out-a-constructor-call-in-java