Apr 8, 2014

Spock Mock Cheatsheet

The Spock testing framework includes powerful mocking capabilities that work well in unit tests. The Spock documentation is extensive, but I often find myself hunting for the syntax of the different mocking mechanisms in Spock. So I created this cheat sheet to help organize the syntax in one concise spot.

I also created a one-page PDF cheatsheet for handy access to this info.

Config for mocking classes

First, we’ll need to include libraries that Spock needs for mocking classes. Grails already defines these dependencies defined, but if you’re using Gradle you’ll need to add them to support mocking classes. Add cglib 2.2 or higher as a dependency if you want to mock classes, and objenesis 1.2 or higher if you want to mock final classes.

Creating mocks

There are a couple different ways to create a mock class. The first is to set the type on when declaring the variable for the mock. Spock will then determine the class of the mock from the type of the variable.

The second way is to use a ‘def’ in the variable definition and pass the class name to the Mock() call

Matching method arguments in mock method calls

Now that we’ve created our mock and used it in the class we’re testing (UserController, in this case), let’s use the mock. Spock provides several different ways to define mock methods and when those mock method definitions will match calls in the code under test.

The most lenient type of argument matching in a mock method call is the underscore, which will match anything that is passed into it:

A slightly more strict form of argument matching is to match on the classes of the mock method arguments:

The strictest form of matching that produces the most thorough tests is to match the exact method arguments:

A substitute for exact argument matching that can come in handy when you don’t have access to the exact object in the test, but can match on properties of the object is the closure form of argument matching:

Verifying mock method call number and order

Spock provides a convenient way to verify the number of times a mock method is called. And in addition to verifying the mock method calls we specify, we can verify no other extra methods are called on our mock objects:

Spock also provides the ability to verify the order in which mock methods are called by specifying the order in multiple ‘then’ blocks:

Defining mock method calls outside of test spec

There may be times where you want to re-use your mock method definitions across multiple test cases. This can be a handy way to reduce copy-paste in test code. You can easily move the mock method definitions into their own method, just be sure to wrap that method call in an ‘interaction’ closure.

Using method arguments in return value

There may be cases where we want to access the arguments passed into the mock method and use those arguments in the return value of the mock call. Spock provides a way to do this by using a closure with the same number and type of arguments as the mock method.

Example code

I put sample tests illustrating these different types of Spock mock usage into Gradle project available on GitHub: https://github.com/craigatk/spock-mock-cheatsheet And the PDF cheatsheet is available as well.

Happy mocking!

About the Author

Object Partners profile.

One thought on “Spock Mock Cheatsheet

  1. Will Buck says:

    Awesome stuff Craig, thanks for throwing this together!

  2. Dave says:

    I have a question. I am trying to test a controller.list() method. I am trying to mock out the object the controller would list. The problem I am running into is attaching the mocked object to the controller so that when I call list(), it sspits out the mocked object. Any ideas?

  3. Sachin says:

    Wow… excellent.
    Thanks a lot, today was my first day on spock and the way you gave details here clarified so easily.

  4. Tarun Arora says:

    Nice Work 🙂

  5. Alejandro says:

    Nice summary of spock’s mocking capabilities. Im new to spock what I have to do in my current project is migrate tests, junit tests mostly that I have to spockarize . Im having some issues trying to mock the HTMLCodec so I wont get this error
    No signature of method: java.lang.String.decodeHTML() is applicable for argument types: () values: []
    Im using grails 4 so I cant use the mockFor(HTMLCodec) and Mock(HTMLCodec) not possible since spock cant mock final classes
    Ive tried GroovyMock(HTMLCodec) also GroovyMock(HTML4Decoder) which is the one that owns the decode(), but nothing worked so far. Any ideas?

Leave a Reply to Tarun Arora Cancel reply

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

Related Blog Posts
Performance Test Liquibase Update
When doing a liquibase update to a database if you’re having performance issues, it can be hard to find out which updates are causing problems. If you need to measure the time to apply each […]
TICK Stack Monitoring for the Non-Technical
TICK – Telegraf, Influx, Chronograf, and Kapacitor – is a method of monitoring your systems and applications. In this article, I discuss in non-technical terms what the difference is between TICK and Prometheus Grafana A […]
Design Systems, Part 1 • Introduction
Business leaders need a practical guide to plan and execute Design System Initiatives. The aim of this series is to be that guide. This installment introduces terms and definitions as a primer on Design Systems.
ML for Translating Dysarthria Speech (Pre-Part 1)
What is Dysarthria? Per the Mayo Clinic, Dysarthria occurs when the muscles you use for speech are weak or you have difficulty controlling them. Dysarthria often causes slurred or slow speech that can be difficult […]