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

Set*_*zer 8 java easymock mocking constructor-injection

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

例:

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.
  }
}
Run Code Online (Sandbox Code Playgroud)

我怎么能期待一个构造函数调用?我可以更改Customer构造函数调用以使用newInstance,但我不确定这是否有帮助.我无法控制new Customer(145)构造函数的主体做什么.

这可能吗?

bet*_*y00 17

您可以使用EasyMock 3.0及更高版本.

Customer cust = createMockBuilder(Customer.class)
     .withConstructor(int.class)
     .withArgs(145)
     .addMockedMethod("someMethod")
     .createMock();
Run Code Online (Sandbox Code Playgroud)


Aug*_*sto 12

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