Skip to content
Tutorials Center
My learning

Topics

Lesson 31 of 38 ยท Testing with Spock

Mocking and Stubbing in Spock

Test collaborating objects with Spock: Mock(), Stub(), Spy(), interaction counts, argument matchers, stubbed return values, ordering and verifying with then:.

Most classes depend on others: a service calls a repository, an order calls a payment gateway. In a unit test you replace the collaborator with a test double so the test is fast, repeatable and focused. Spock builds this into the framework, with no extra library, and uses its own compact syntax for describing what should happen.

Spock and Groovy cannot run on this site, so the Spock code is read-only. The Java stand-ins build a counting test double with java.lang.reflect.Proxy so you can see what Spock does for you.

Three kinds of double

Kind Created with Use it for
Stub Stub(Type) Supplies canned answers. No verification.
Mock Mock(Type) Supplies answers and checks the interactions.
Spy Spy(Type) Wraps a real object: real behavior, but you may override or verify calls.

A Stub is for "give me data", a Mock is for "did you call this?". Use the weakest double that works: stubs for inputs, mocks only for outputs that matter, such as sending an email.

Stubbing: return values

GROOVY
import spock.lang.Specification

class PriceServiceSpec extends Specification {

  def "total uses the exchange rate"() {
    given:
    def rates = Stub(RateProvider)
    rates.rate("EUR", "USD") >> 1.1G
    def service = new PriceService(rates)

    expect:
    service.convert(100, "EUR", "USD") == 110
  }
}

The >> operator means "returns". Variants:

  • >> 5 always returns 5.
  • >>> [1, 2, 3] returns 1, then 2, then 3, then repeats the last value.
  • >> { args -> args[0] * 2 } computes from the arguments, and >> { throw new IOException() } throws.
  • _ >> "x" stubs any call; rates.rate(_, "USD") >> 1.1 matches any first argument.

Mocking: verifying interactions

GROOVY
def "sends a welcome email once"() {
  given:
  def mailer = Mock(Mailer)
  def signup = new SignupService(mailer)

  when:
  signup.register("[email protected]")

  then:
  1 * mailer.send("[email protected]", _)
}

The line 1 * mailer.send(...) is an interaction: "exactly one call to send with this first argument and anything as the second". The count can be 0 * (never), (1..3) *, (_..2) * (at most two), or _ * (any). Placing it in then: verifies after the when: block runs.

Argument constraints (matchers):

Form Meaning
"x" equals "x"
_ any single argument
*_ any number of arguments
!"x" anything but "x"
_ as String any String
{ it.startsWith("a") } a closure condition
!null any non-null

Method and target wildcards also work: 1 * _.send(*_) (any object), 0 * _ (no other interaction at all, great for strict tests).

Stubbing and verifying together

GROOVY
then:
1 * repo.save({ it.name == "Ada" }) >> { User u -> u.id = 7; u }

This verifies exactly one save call with a user named Ada and makes it return the user with an id. Combine both only when you need to; otherwise prefer a Stub for returns and an interaction for outputs.

Ordering

Interactions in different then: blocks must happen in that order:

GROOVY
then:
1 * db.begin()
then:
1 * db.insert(_)
then:
1 * db.commit()

Spies

GROOVY
def calc = Spy(Calculator)

when:
calc.add(1, 2)

then:
1 * calc.add(1, 2)       // verifies, and the real method still runs
calc.add(1, 2) == 3

A Spy is a partial mock. Stub one method and the others stay real: calc.slowCall() >> 5. Spy only when a collaborator cannot be refactored; heavy spying signals a design with too many responsibilities.

Mocking classes and final things

Mock(SomeClass) works for interfaces out of the box. For classes you need byte-buddy and objenesis on the classpath (common in Gradle builds); final classes and static methods need extra tools (such as GroovyMock and GroovySpy for Groovy objects, which can mock constructors and statics with GroovySpy(global: true)).

Dos and don'ts

  1. Test behavior that matters. Verifying every internal call makes tests brittle.
  2. Prefer 0 * _ at the end of strict tests to detect unwanted calls.
  3. Do not mock types you do not own, and never value objects; build real ones.
  4. Keep stubs close to the data they supply so the feature reads top to bottom.

Try it: a counting mock with Proxy (stand-in)

The mock records calls, returns canned values (a "stub"), and lets the test verify counts afterward.

Java Stand-in: mock that counts and answers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try it: sequential stub answers (stand-in)

Spock's >>> [1, 2, 3] returns values one after another and repeats the last. This helper does the same.

Java Stand-in: the >>> operator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which double should you use when you only need canned return values?

    A Stub supplies data and does not verify interactions, which keeps tests less brittle.
  2. 2. What does 1 * mailer.send(_, _) in a then: block check?

    The number before * is the expected call count for the matching interaction.
  3. 3. What does >>> [1, 2, 3] do?

    specifies a sequence of return values for consecutive calls.

  4. 4. What is a Spy?

    A spy keeps real behavior by default, and you override or verify only what you need.

Summary

  • Stubs return canned data (>>), mocks also verify interactions (1 * obj.method(args)), spies wrap real objects.
  • Argument matchers: literal values, _, *_, !x, type checks and closures.
  • Use 0 * _ for strict tests and then: blocks in sequence for ordering.
  • Prefer the weakest double and test behavior, not implementation detail.

Next: Gradle Build Scripts