I'm using Spock and my class to test is wrapped in a Spy. 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.
I tried this:
1 * classToTest.methodName(_)
but the actual method is still called.
How do I stub out a void method using Spock?
Stubbing Method Calls A stub is a controllable replacement of an existing class dependency in our tested code. This is useful for making a method call that responds in a certain way.
Spock is a testing and specification framework for Java and Groovy applications. What makes it stand out from the crowd is its beautiful and highly expressive specification language. Thanks to its JUnit runner, Spock is compatible with most IDEs, build tools, and continuous integration servers.
Right click on the project > Properties > Java Build Bath > Add External Jars and add spock-core-0.6-groovy-1.8. jar and check if Groovy Libraries are there in Build Path or not. If not click on Add Library and select Groovy Runtime Libraries and restart Eclipse. Now you should be able to run.
You can just stub it with null
...
Given the following Java class:
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:
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 == []
}
}
You could also return an empty closure (instead of a null):
1 * complex.sideEffect(_) >> {}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With