DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • When a Coding Agent Fixes the Test Instead of the Bug
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Your Visual Regression Suite Is Mostly Testing Anti-Aliasing
  • From Issue to Reviewable Patch: Build a Sandboxed Coding Agent With Deep Agents and Automated Tests

Trending

  • Architecture Review Boards for Generative AI: A Framework for Governance, Risk Management, and Responsible Adoption
  • New York City Taxi Trips: Putting Neo4j and DuckDB to Work
  • When a Coding Agent Fixes the Test Instead of the Bug
  • How to Build Your Own AI SRE From Scratch

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. An introduction to Spock

An introduction to Spock

By 
John Ferguson Smart
·
Nov. 04, 10 · Interview
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
39.7K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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"() {
given:
def calculator = new RomanCalculator()
when:
def result = calculator.add("I", "I")
then:
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(com.wakaleo.training.spocktutorial.RomanCalculatorSpec) 
Time elapsed: 0.33 sec <<< FAILURE!
Condition not satisfied:

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

at com.wakaleo.training.spocktutorial
.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"() {
when:
def result = calculator.add("I", "I")
then:
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"() {
when:
def result = calculator.add(a, b)

then:
result == sum

where:
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:

  given:
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.

From http://www.wakaleo.com/blog/303-an-introduction-to-spock

Spock (testing framework) Testing

Opinions expressed by DZone contributors are their own.

Related

  • When a Coding Agent Fixes the Test Instead of the Bug
  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • Your Visual Regression Suite Is Mostly Testing Anti-Aliasing
  • From Issue to Reviewable Patch: Build a Sandboxed Coding Agent With Deep Agents and Automated Tests

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook