The Spock testing framework currently does not support partial mocks. It is easy to mock out a class, but not individual methods in a class.
In almost all cases, this makes sense to me. If you really only want to mock out only one method, maybe you need to refactor the code to create a new class. While this is good in theory, it is not always practically possible.
In these cases, you could use Groovy’s meta-programming to accomplish partial mocks.
Let’s say you have a simple class like this:
class MyClass {
def doSomethingCool(){
if(findBooleanValue()){
return 1
} else {
return 2
}
}
def findBooleanValue() {
//do something complicated to determine value
return true
}
}
If I just wanted to mock out the findBooleanValue method, but test the actual functionality of the doSomethingCool() method, I could write a spock test like this:
def 'test with partial mocks' () {
given: 'an instance of the class to test'
def testClass = new MyClass()
and: 'partial mock findBooleanValue method'
testClass.metaClass.findBooleanValue = {false}
expect: 'the method should be overridden'
testClass.doSomethingCool() == 2
}
Here I used simply used Groovy’s metaClass to change how the findBooleanValue method acts.

You can also try the @Use annotation.
https://github.com/spockframework/spock/blob/groovy-1.8/spock-core/src/main/java/spock/util/mop/Use.java
It’s one of the many under-documented gems of Spock. It works just like a category on your CUT and you can override your ‘expensive’ method.
The @Use annotation can be used at the class level to cover all your tests or at the individual method level.
Example Gist
That is a good tip, and a little cleaner than using the metaClass stuff. Thanks for the example code as well.
Software Development
Nice blog! It is very useful and interesting post. Thanks! for sharing such a great post. Please keep posting about web design and development related stuff on your blog.