是否有可能(例如捕获)在从新对象调用某个方法时返回一个模拟对象?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