John is an experienced consultant specialising in Enterprise Java, Web Development, and Open Source technologies, currently based in Sydney, Australia. Well known in the Java community for his many published articles, and as author of Java Power Tools and Jenkins: The Definitive Guide, and founder of the open source Thucydides Automated Acceptance Test Library project, John helps organisations to optimize their Java development processes and infrastructures and provides training and mentoring in agile development, automated testing practices, continuous integration and delivery, and open source technologies in general. John is the CEO of Wakaleo Consulting, and runs several Training Courses on open source Java development tools and best practices. John is a DZone MVB and is not an employee of DZone and has posted 127 posts at DZone. You can read more from them at their website. View Full User Profile

An introduction to Spock

  • submit to reddit

Spock is an open source testing framework for Java and Groovy that has been attracting a growing following, especially in the Groovy community. It lets you write concise, expressive tests, using a quite readable BDD-style notation. It even comes with its own mocking library built in.

Oh. I thought he was a sci-fi character. Can I see an example?

Sure. Here's a simple one from a coding kata I did recently:

import spock.lang.Specification;

class RomanCalculatorSpec extends Specification {
def "I plus I should equal II"() {
def calculator = new RomanCalculator()
def result = calculator.add("I", "I")
result == "II"

In Spock, you don't have tests, you have specifications. These are normal Groovy classes that extend the Specifications class, which is actually a JUnit class. Your class contains a set of specifications, represented by methods with funny-method-names-in-quotes™. The funny-method-names-in-quotes™ take advantage of some Groovy magic to let you express your requirements in a very readable form. And since these classes are derived from JUnit, you can run them from within Eclipse like a normal Groovy unit test, and they produce standard JUnit reports, which is nice for CI servers.

Another thing: notice the structure of this test? We are using given:, when: and then: to express actions and expected outcomes. This structure is common in Behaviour-Driven Development, or BDD, frameworks like Cucumber and easyb. Though Spock-style tests are generally more concise more technically-focused than tools like Cucumber and easyb, which are often used for automating acceptance tests. But I digress...

Actually, the example I gave earlier was a bit terse. We could make our intent clearer by adding text descriptions after the when: and then: labels, as I've done here:

def "I plus I should equal II"() {
when: "I add two roman numbers together"
def result = calculator.add("I", "I")

then: "the result should be the roman number equivalent of their sum"
result == "II"

This is an excellent of clarifying your ideas and documenting your API.

But where are the AssertEquals statements?

Aha! I'm glad you asked! Spock uses a feature called Power Asserts. The statement after the then: is your assert. If this test fails, Spock will display a detailed analysis of what went wrong, along the following lines:

I plus I should equal II( 
Time elapsed: 0.33 sec <<< FAILURE!
Condition not satisfied:

result == "II"
| |
I false
1 difference (50% similarity)

.RomanCalculatorSpec.I plus I should equal II(RomanCalculatorSpec.groovy:17)

Nice! But in JUnit, I have @Before and @After for fixtures. Can I do that in Spock?

Sure, but you don't use annotations. Instead you implement setup() and cleanup() methods (which are run before and after each specification). I've added one here to show you what they look like:

import spock.lang.Specification;

class RomanCalculatorSpec extends Specification {

def calculator
def setup() {
calculator = new RomanCalculator()

def "I plus I should equal II"() {
def result = calculator.add("I", "I")
result == "II"

You can also define a setupSpec() and cleanupSpec(), which are run just before the first test and just after the last one.

I'm a big fan of parameterized tests in JUnit 4. Can I do that in Spock!

You sure can! In fact it's one of Spock's killer features!

  def "The lowest number should go at the end"() {
def result = calculator.add(a, b)

result == sum

a | b | sum
"X" | "I" | "XI"
"I" | "X" | "XI"
"XX" | "I" | "XXI"
"XX" | "II" | "XXII"
"II" | "XX" | "XXII"

This code will run the test 5 times. The variables a, b, and sum are initialized from the rows in the table in the where: clause. And if any of the tests fail, you get

That's pretty cool too. What about mocking? Can I use Mockito?

Sure, if you want. but Spock actually comes with it's own mocking framework, which is pretty neat. You set up a mock or a stub using the Mock() method. I've shown two possible ways to use this method here:

Subscriber subscriber1 = Mock()
def subscriber2 = Mock(Subscriber)

You can set these mocks up to behave in certain ways. Here are a few examples. You can say a method should return a certain value using the >> operator:

 subscriber1.isActive() >> true
subscriber2.isActive() >> false

Or you could get a method to throw an exception when it is called:

    subscriber.activate() >> { throw new BlacklistedSubscriberException() } 

Then you can test outcomes in a few different ways. Here is a more complicated example to show you some of your options:

def "Messages published by the publisher should only be received by active subscribers"() {

given: "a publisher"
def publisher = new Publisher()

and: "some active subscribers"
Subscriber activeSubscriber1 = Mock()
Subscriber activeSubscriber2 = Mock()

activeSubscriber1.isActive() >> true
activeSubscriber2.isActive() >> true

publisher.add activeSubscriber1
publisher.add activeSubscriber2

and: "a deactivated subscriber"
Subscriber deactivatedSubscriber = Mock()
deactivatedSubscriber.isActive() >> false
publisher.add deactivatedSubscriber

when: "a message is published"
publisher.publishMessage("Hi there")

then: "the active subscribers should get the message"
1 * activeSubscriber1.receive("Hi there")
1 * activeSubscriber2.receive({ it.contains "Hi" })

and: "the deactivated subscriber didn't receive anything"
0 * deactivatedSubscriber.receive(_)

That does look neat. So what is the best place to use Spock?

Spock is great for unit or integration testing of Groovy or Grails projects. On the other hand, tools like easyb amd cucumber are probably better for automated acceptance tests - the format is less technical and the reporting is more appropriate for non-developers.


Published at DZone with permission of John Ferguson Smart, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)



Howard Lewis Ship replied on Thu, 2010/11/04 - 10:08am

I started learning Spock myself recently; I'm using it on a new, small framework I'm developing (the framework is all Java, but the tests are all Spock). I'm impressed by DSL it provides, and the general refinement and ease of use. I haven't tapped into the mock object support yet, but possibly soon. I certainly hit the "test doldrums" before starting to use Groovy for testing about 6 months ago, Spock is the evolution of that (for Tapestry, I'm increasingly using TestNG and Groovy together).

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.