我有一个静态方法,在多个地方使用,主要是在静态初始化块中。它接受一个 Class 对象作为参数,并返回该类的实例。
我只想在特定的 Class 对象用作参数时模拟此静态方法。但是,当从其他地方使用不同的 Class 对象调用该方法时,它会返回 null。
如果参数不是模拟的参数,我们如何让静态方法执行实际的实现?
class ABC{
void someMethod(){
Node impl = ServiceFactory.getImpl(Node.class); //need to mock this call
impl.xyz();
}
}
class SomeOtherClass{
static Line impl = ServiceFactory.getImpl(Line.class); //the mock code below returns null here
}
class TestABC{
@Mocked ServiceFactory fact;
@Test
public void testSomeMethod(){
new NonStrictExpectations(){
ServiceFactory.getImpl(Node.class);
returns(new NodeImpl());
}
}
}
你想要的是一种“部分嘲笑”的形式,特别是dynamic部分嘲笑 http://jmockit.org/tutorial/BehaviorBasedTesting.html#dynamicPartial在 JMockit API 中:
@Test
public void testSomeMethod() {
new NonStrictExpectations(ServiceFactory.class) {{
ServiceFactory.getImpl(Node.class); result = new NodeImpl();
}};
// Call tested code...
}
只有符合记录期望的调用才会被嘲笑。当调用动态模拟类时,其他人将执行真正的实现。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)