Search⌘ K
AI Features

Mocking and Lists

Explore how Spock simplifies Java testing by enabling easy mocking of interfaces and using lists or tables for data-driven tests. Understand how to control expected calls with wildcards, use ranges for method invocation limits, and write clear tests that handle exceptions, making your tests more readable and maintainable.

Mocking

Mocking interfaces is extremely easy in Spock. Simply use the Mock method, as shown in the following example (where Subscriber is an interface):

class APublisher extends Specification {
 def publisher = new Publisher()
 def subscriber = Mock(Subscriber)

Now subscriber is a mocked object. We can implement methods simply using the overloaded operator >> as shown below.

def "can cope with misbehaving subscribers"() {
 subscriber.receive(_) >> { throw new Exception() }

 when:
 publisher.send("event")
 publisher.send("event")

...