EasyMock - 从新对象返回的模拟对象

EasyMock - mock object returned from new Object

当从新对象调用方法时,是否可以通过捕获来 return 模拟?

为了更具体一点:

SecurityInterface client = new SecurityInterface();
port = client.getSecurityPortType(); --> I want to mock this.

easymock 版本:3.3.1

不 - 这正是您需要从 类 中设计的静态耦合,以使它们可测试。

您需要通过您注入的供应商或工厂提供 SecurityInterface:然后您可以注入一个在生产代码中调用 new 的实例,以及一个 returns 测试代码中的模拟。

class MyClass {
  void doSomething(SecurityInterfaceSupplier supplier) {
    Object port = supplier.get().getSecurityPortType();
  }
}

interface SecurityInterfaceSupplier {
  SecurityInterface get();
}

class ProductionSecurityInterfaceSupplier implements SecurityInterfaceSupplier {
  @Override public SecurityInterface get() { return new SecurityInterface(); }
}

class TestingSecurityInterfaceSupplier implements SecurityInterfaceSupplier {
  @Override public SecurityInterface get() { return mockSecurityInterface; }
}

是的,如果您还使用 Powermock,您的测试代码可以拦截对 new 和 return 的调用,而不是模拟。所以你可以 return 模拟 new SecurityInterface() 然后模拟它的 getter

Powermock 与 Easymock 兼容

@RunWith(PowerMockRunner.class)
@PrepareForTest( MyClass.class )
public class TestMyClass {

@Test
public void foo() throws Exception {
   SecurityInterface mock = createMock(SecurityInterface.class);

    //intercepts call to new SecurityInterface and returns a mock instead
    expectNew(SecurityInterface.class).andReturn(mock);
    ...
    replay(mock, SecurityInterface.class);
    ...
    verify(mock, SecurityInterface.class);
}

}