EasyMock:在java中模拟一个构造函数调用

我在这个板上看了类似的问题,但没有一个回答我的问题。 这听起来很奇怪,但是可以在你正在嘲笑的对象上模拟一个构造函数调用。

例:

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)构造函数的主体。

这可能吗?

你可以使用EasyMock 3.0及以上版本。

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

你不能用easymock做到这一点,因为它不支持模拟构造函数。 有一个名为powermock的库可以做到这一点,据我所知,它是唯一一个可以在Java中存根构造函数和静态方法的模拟库。

 import static org.powermock.api.easymock.PowerMock.expectNew; instance = new UsesNewToInstantiateClass(); expectNew(AnyOldClass.class).andReturn(anyClass); 

这就是为什么你想要注入你的依赖项(通过Guice或类似的包)而不是在你的类中创建它们。

那你就不必嘲笑他们的建筑。

这假定(a)这是您可以更改的代码,以及(b)有问题的对象足够复杂,您应该注入它们。 在你的类中构造简单的对象很好,但是你不应该嘲笑它们。