Skip to content

Instantly share code, notes, and snippets.

@bdkosher
Created January 28, 2015 14:56
Show Gist options
  • Save bdkosher/128792f7f290bb4bc6ba to your computer and use it in GitHub Desktop.
Save bdkosher/128792f7f290bb4bc6ba to your computer and use it in GitHub Desktop.
Canonical Spock mocking example.
// http://www.infoq.com/presentations/groovy-test-java-spock @ 17:00
import spock.lang.Specification
class Publisher {
def subscribers = []
def send(event) {
subscribers.each {
try {
it.receive(event)
} catch (Exception e) {}
}
}
}
interface Subscriber {
def receive(event)
}
class PublisherSpec extends Specification {
def pub = new Publisher()
def sub1 = Mock(Subscriber)
def sub2 = Mock(Subscriber)
def setup() {
pub.subscribers << sub1 << sub2
}
def "delivers events to all subscribers"() {
when:
pub.send("event")
then:
1 * sub1.receive("event") // read as "sub1's receive method is called with arg value 'event' exactly one time
1 * sub2.receive("event")
}
def "can cope with misbehaving subscribers"() {
sub1.receive(_) >> { throw new Exception() } // read as "when sub1's receive method is called with any value, throw Exception
when:
pub.send("event1")
pub.send("event2")
then:
1 * sub2.receive("event1")
1 * sub2.receive("event2")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment