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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Testing Asynchronous Operations in Spring With Spock and Byteman
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • That Can Not Be Tested!: Spring Cache and Retry

Trending

  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  • Concourse CI/CD Pipeline: Webhook Triggers
  • Blue Skies Ahead: An AI Case Study on LLM Use for a Graph Theory Related Application
  • Immutable Secrets Management: A Zero-Trust Approach to Sensitive Data in Containers
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Using Spock to Test Spring Classes

Using Spock to Test Spring Classes

By 
Geraint Jones user avatar
Geraint Jones
·
Oct. 23, 12 · Interview
Likes (1)
Comment
Save
Tweet
Share
48.5K Views

Join the DZone community and get the full member experience.

Join For Free

As the previous post mentioned, Spock is a powerful DSL built on Groovy ideal for TDD and BDD testing and this post will describe how easy it is to use Spock to test Spring classes, in this case the CustomerService class from the post Using Spring Data to access MongoDB. It will also cover using Spock for mocking.

Spock relies heavily on the Spring's TestContext framework and does this via the @ContextConfiguration annotation. This allows the test specification class to load an application context from one or more locations.

This will then allow the test specification to access beans either via the annotation @Autowired or @Resource. The test below shows how an injected CusotmerService instance can be tested using Spock and the Spring TestContext: (This is a slightly contrived example as to properly unit test the CustomerService class as you would create a CustomerService class in the test as opposed to one created and injected by Spring.)

package com.city81.mongodb.springdata.dao
 
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
 
import spock.lang.*
 
import com.city81.mongodb.springdata.entity.Account
import com.city81.mongodb.springdata.entity.Address
import com.city81.mongodb.springdata.entity.Customer
 
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
class CustomerServiceTest extends Specification {
 
 @Autowired
 CustomerService customerService
  
  
 def setup() {
  customerService.dropCustomerCollection()
 }
  
 def "insert customer"() {
   
  setup:
   
  // setup test class args
  Address address = new Address()
  address.setNumber("81")
  address.setStreet("Mongo Street")
  address.setTown("City")
  address.setPostcode("CT81 1DB")
  
  Account account = new Account()
  account.setAccountName("Personal Account")
  List<Account> accounts = new ArrayList<Account>()
  accounts.add(account)
   
  Customer customer = new Customer()
  customer.setAddress(address)
  customer.setName("Mr Bank Customer")
  customer.setAccounts(accounts)
 
  when:
  customerService.insertCustomer(customer)
   
  then:
  def customers = customerService.findAllCustomers()
  customers.size == 1
  customers.get(0).name == "Mr Bank Customer"
  customers.get(0).address.street == "Mongo Street"
   
 }
}

The problem though with the above test is that MongoDB needs to be up and running so to remove this dependency we can Mock out the interaction the database. Spock's mocking framework provides many of the features you'd find in similar frameworks like Mockito.

The enhanced CustomerServiceTest mocks the CustomerRepository and sets the mocked object on the CustomerService. 

package com.city81.mongodb.springdata.dao
 
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.test.context.ContextConfiguration
 
import spock.lang.*
 
import com.city81.mongodb.springdata.entity.Account
import com.city81.mongodb.springdata.entity.Address
import com.city81.mongodb.springdata.entity.Customer
 
@ContextConfiguration(locations = "classpath:spring/applicationContext.xml")
class CustomerServiceTest extends Specification {
 
 @Autowired
 CustomerService customerService
  
 CustomerRepository customerRepository = Mock()
  
 def setup() {
  customerService.customerRepository = customerRepository
  customerService.dropCustomerCollection()
 }
  
 def "insert customer"() {
   
  setup:
     
  // setup test class args
  Address address = new Address()
  address.setNumber("81")
  address.setStreet("Mongo Street")
  address.setTown("City")
  address.setPostcode("CT81 1DB")
  
  Account account = new Account()
  account.setAccountName("Personal Account")
  List<Account> accounts = new ArrayList<Account>()
  accounts.add(account)
   
  Customer customer = new Customer()
  customer.setAddress(address)
  customer.setName("Mr Bank Customer")
  customer.setAccounts(accounts)
   
  when:
  customerService.insertCustomer(customer)
   
  then:
  1 * customerRepository.save(customer)
   
 }
  
 def "find all customers"() {
  
  setup:
   
  // setup test class args
  Address address = new Address()
  address.setStreet("Mongo Street")
   
  Customer customer = new Customer()
  customer.setAddress(address)
  customer.setName("Mr Bank Customer")
   
  // setup mocking 
  def mockCustomers = []
  mockCustomers << customer
  customerRepository.findAll() >> mockCustomers
   
  when:
  def customers = customerService.findAllCustomers()
   
  then:
  customers.size() == 1 
  customers.get(0).name == "Mr Bank Customer"
   
 }
  
}

The CustomerRepository is by way of name and type although it could be inferred by just the name eg

def customerRepository = Mock(CustomerRepository)

The injected customerRepository is overwritten by the mocked instance and then in the test setup, functionality can be mocked.

In the then block of the insert customer feature, the number of interactions with the save method of customerRepository is tested and in the find all customers feature, the return list of customers from the findAll call is a mocked List,as opposed to one retrieved from the database.

More detail on Spock's mocking capabilities can be found on the project's home page.

 

unit test Spock (testing framework) Spring Framework

Published at DZone with permission of Geraint Jones, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Asynchronous Operations in Spring With Spock and Byteman
  • Comprehensive Guide to Unit Testing Spring AOP Aspects
  • Be Punctual! Avoiding Kotlin’s lateinit In Spring Boot Testing
  • That Can Not Be Tested!: Spring Cache and Retry

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!