[英]Stub a void method in a Spy object with Spock
I'm using Spock and my class to test is wrapped in a Spy. 我正在使用Spock,我的班级测试被包裹在间谍中。 I want to isolate the method being tested, so I'm trying to stub out other methods that are called from the method being tested.
我想隔离正在测试的方法,所以我试图找出从被测试方法中调用的其他方法。 Normally I would use something like this:
通常我会使用这样的东西:
1 * classToTest.methodName(_) >> stubbed_return_value
My problem is this: methodName
is a void method. 我的问题是这样的:
methodName
是一个void方法。 I tried this: 我试过这个:
1 * classToTest.methodName(_)
but the actual method is still called. 但实际的方法仍然被调用。
How do I stub out a void method using Spock? 如何使用Spock删除void方法?
You can just stub it with null
... 你可以用
null
来存根...
Given the following Java class: 给定以下Java类:
public class Complex {
private final List<String> sideEffects = new ArrayList<>();
protected void sideEffect(String name) {
sideEffects.add("Side effect for " + name);
}
public int call(String name) {
sideEffect(name);
return name.length();
}
public List<String> getSideEffects() {
return sideEffects;
}
}
We want to hide the sideEffect
method, so nothing is done by it, so we can use the following spec: 我们想要隐藏
sideEffect
方法,所以没有做任何事情,所以我们可以使用以下规范:
class ComplexSpec extends Specification {
def 'we can ignore void methods in Spies'() {
given:
Complex complex = Spy()
when:
int result = complex.call('tim')
then:
result == 3
1 * complex.sideEffect(_) >> null
complex.sideEffects == []
}
}
您还可以返回一个空闭包(而不是null):
1 * complex.sideEffect(_) >> {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.