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

时间:2015-10-20 16:13:10

标签: java junit easymock

例如,捕获是否有可能在从新对象调用方法时返回模拟?

使其更具体:

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

easymock版本:3.3.1

2 个答案:

答案 0 :(得分:3)

是的,如果您还使用Powermock,您的测试代码可以拦截对Person *billy = [Person initWithStuff:stuff]; 的调用并返回模拟。所以你可以为Person *bobby = billy; bobby.name = @"Bobby"; 返回一个模拟,然后模拟它的getter

Powermock与Easymock兼容

new

答案 1 :(得分:1)

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

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

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; }
}
相关问题