【发布时间】:2011-10-04 19:50:00
【问题描述】:
我看过这个板上的类似问题,但没有一个回答我的问题。这听起来很奇怪,但是否可以模拟出对您正在模拟的对象的构造函数调用。
例子:
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,但我不确定这是否会有所帮助。我无法控制 new Customer(145) 构造函数的主体的作用。
这可能吗?
【问题讨论】:
-
最好不要在构造函数中建立数据库连接。使用它们将连接注入到类中。
-
同意。但我无法控制 Customer 构造函数逻辑。
标签: java mocking easymock constructor-injection