Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stub a void method in a Spy object with Spock

Tags:

java

groovy

spock

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?

like image 782
DwB Avatar asked Feb 28 '17 15:02

DwB


People also ask

What is stub in 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.

What is Spock in Java?

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.

How do I run Spock test in eclipse?

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.


2 Answers

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 == []
    }
}
like image 87
tim_yates Avatar answered Oct 18 '22 05:10

tim_yates


You could also return an empty closure (instead of a null):

1 * complex.sideEffect(_) >> {}
like image 36
vadim Avatar answered Oct 18 '22 04:10

vadim