Spock: mocks and stubs

A unit test needs a collaborator it does not want to run: a mail server, a clock, a repository. Spock calls the two replacements a Stub, which answers a call, and a Mock, which also records the calls so the test can assert on them.

The collaborators

The real mailer throws, which is what a collaborator the test must not reach looks like. The directory answers a name, and the service between them is the class under test.

Welcome.groovy

class Mailer { void send(String to, String text) { throw new UnsupportedOperationException('the real mailer is not used in a test') } } class Directory { String nameOf(String id) { 'nobody' } } class Welcome { Mailer mailer Directory directory void greet(String id) { mailer.send(id, "Welcome, ${directory.nameOf(id)}") } }

A mock and a stub

WelcomeSpec.groovy

import spock.lang.Specification class WelcomeSpec extends Specification { def 'sends one message to the name the directory gives'() { given: 'a stub directory and a mock mailer' def directory = Stub(Directory) { nameOf('1') >> 'Ada' } def mailer = Mock(Mailer) def welcome = new Welcome(directory: directory, mailer: mailer) when: 'the new member is greeted' welcome.greet('1') then: 'exactly one message goes out, with the name from the stub' 1 * mailer.send('1', 'Welcome, Ada') } }

Stub(Directory) { nameOf('1') >> 'Ada' } answers one call with one value. 1 * mailer.send('1', 'Welcome, Ada') in the then: block is an interaction: the test fails when the call happens twice, not at all, or with other arguments.

Run it

CP=/opt/spock/spock-core-2.4-groovy-5.0.jar:/opt/spock/byte-buddy-1.17.5.jar:/opt/spock/geantyref-1.3.16.jar:/opt/spock/hamcrest-3.0.jar:/opt/spock/objenesis-3.4.jar:/opt/groovy/lib/groovy-5.0.8.jar
groovyc -cp "$CP" -d out Welcome.groovy WelcomeSpec.groovy
junit execute --class-path "out:$CP" --select-class WelcomeSpec --disable-ansi-colors


Thanks for using JUnit! Support its development at https://junit.org/sponsoring

╷
├─ JUnit Platform Suite ✔
├─ JUnit Jupiter ✔
├─ JUnit Vintage ✔
└─ Spock ✔
   └─ WelcomeSpec ✔
      └─ sends one message to the name the directory gives ✔

Test run finished after 3655 ms
[ 5 containers found ]
[ 0 containers skipped ]
[ 5 containers started ]
[ 0 containers aborted ]
[ 5 containers successful ]
[ 0 containers failed ]
[ 1 tests found ]
[ 0 tests skipped ]
[ 1 tests started ]
[ 0 tests aborted ]
[ 1 tests successful ]
[ 0 tests failed ]

The mock answered nothing, so the call had to be the expected one; the stub answered the name, so the message text could be checked exactly. That is the division of the two: a stub feeds the code, a mock is the assertion.

Related

Article author: Arthur Isaev

Banner image