Stub a void method in a Spy object with Spock
Asked Answered
P

2

18

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?

Presidency answered 28/2, 2017 at 15:25 Comment(1)
Just in case anyone who is as clueless as myself gets here at some time: in Spock you can't mock private methods: they will just run as normal with a Spy. I found this "limitation" of Spock (it's actually because it does not make testing sense) surprising, in the sense that you can call such methods from your Spy (and seem to mock them) in your testing code... It might possibly be nice if Spock could disallow this or flag it as an error...Hanger
S
19

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 == []
    }
}
Solent answered 28/2, 2017 at 16:31 Comment(0)
M
8

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

1 * complex.sideEffect(_) >> {}
Marchesa answered 15/11, 2018 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.