DZone
Java Zone
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
Over 2 million developers have joined DZone.
Log In / Join
  • Refcardz
  • Trend Reports
  • Webinars
  • Zones
  • |
    • Agile
    • AI
    • Big Data
    • Cloud
    • Database
    • DevOps
    • Integration
    • IoT
    • Java
    • Microservices
    • Open Source
    • Performance
    • Security
    • Web Dev
DZone > Java Zone > An introduction to Spock

An introduction to Spock

John Ferguson Smart user avatar by
John Ferguson Smart
·
Nov. 04, 10 · Java Zone · Interview
Like (4)
Save
Tweet
36.54K Views

Join the DZone community and get the full member experience.

Join For Free

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.

Popular on DZone

  • Usage of Java Streams and Lambdas in Selenium WebDriver
  • Troubleshooting Memory Leaks With Heap Profilers
  • How to Configure Git in Eclipse IDE
  • Chopping the Monolith

Comments

Java Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends:

DZone.com is powered by 

AnswerHub logo