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
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Trending

  • Non-Project Backlog Management for Software Engineering Teams
  • Unlocking the Benefits of a Private API in AWS API Gateway
  • Role of Cloud Architecture in Conversational AI
  • A Complete Guide to Modern AI Developer Tools
  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 user avatar
John Ferguson Smart
·
Nov. 04, 10 · Interview
Likes (4)
Comment
Save
Tweet
Share
38.1K 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.

Related

  • Modern Test Automation With AI (LLM) and Playwright MCP
  • AI-Driven Test Automation Techniques for Multimodal Systems
  • Debugging With Confidence in the Age of Observability-First Systems
  • Accelerating Debugging in Integration Testing: An Efficient Search-Based Workflow for Impact Localization

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!