简体   繁体   中英

EasyMock - mock object returned from new Object

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

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM