EasyMock - mock object returned from new Object

﹥>﹥吖頭↗ 提交于 2019-12-11 00:52:36

问题


Is it possible, with a capture for example, to return a mock when a method is called from a new object?

To make it more concrete:

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

easymock version: 3.3.1


回答1:


Yes, if you also use Powermock your test code can intercept the calls to new and return a mock instead. So you can return a mock for new SecurityInterface() and then mock its getter

Powermock is compatible with 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);
}

}



回答2:


No - this is exactly the sort of static coupling that you need to design out of your classes in order to make them testable.

You would need to provide the SecurityInterface via a supplier or a factory which you inject: you can then inject an instance which invokes new in your production code, and an instance which returns a mock in your test code.

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; }
}


来源:https://stackoverflow.com/questions/33241635/easymock-mock-object-returned-from-new-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!