是否有可能(例如捕獲)在從新對象調用某個方法時返回一個模擬對象?EasyMock - 從新對象返回的模擬對象
爲了使它更具體:
SecurityInterface client = new SecurityInterface();
port = client.getSecurityPortType(); --> I want to mock this.
EasyMock的版本:3.3.1
是否有可能(例如捕獲)在從新對象調用某個方法時返回一個模擬對象?EasyMock - 從新對象返回的模擬對象
爲了使它更具體:
SecurityInterface client = new SecurityInterface();
port = client.getSecurityPortType(); --> I want to mock this.
EasyMock的版本:3.3.1
是的,如果你還用Powermock測試代碼可以攔截調用new
,並返回一個模擬代替。所以,你可以返回一個模擬爲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);
}
}
否 - 這正是那種靜態耦合的,你需要爲了使設計出的類他們可測試。
您將需要提供通過供應商或工廠,你注入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; }
}
這樣做的問題是,我無法在CDI/EJB環境工作兼容,我可以」注入任何東西。否則,我確實無法做到這一點。忘了提這個.. – GregD
嗯..沒想到powermock。好建議! – GregD