Partial Mocks with Spock on Groovy/Grails

Post by Matt Nohr

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(){
            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.

This entry was posted in Software Development and tagged , , , . Bookmark the permalink.

Related Posts:

4 Responses to Partial Mocks with Spock on Groovy/Grails

  1. Zan Thrash says:

    You can also try the @Use annotation.

    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

  2. Matt Nohr says:

    That is a good tip, and a little cleaner than using the metaClass stuff. Thanks for the example code as well.

  3. 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.

  4. Yash Vyas says:

    You could also use Spies, with the latest version of Spock for this.

    Since I came accross this page first when looking around i thought id mention it here.

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>