An introduction to Spock

DZone 's Guide to

An introduction to Spock

· Java Zone ·
Free Resource

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(com.wakaleo.training.spocktutorial.RomanCalculatorSpec) 
Time elapsed: 0.33 sec <<< FAILURE!
Condition not satisfied:

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

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"() {
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.

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


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}