Chapter 4. Writing unit tests with Spock

 

This chapter covers

  • Working with Spock blocks
  • Understanding the lifecycle of a test
  • Improving readability of Spock tests
  • Using reusable JUnit features

All the Spock tests you’ve seen so far have been presented to you as a finished unit test, with no explanation of how to reach that particular code structure. You’re probably eager to create your own Spock tests from scratch. In this chapter, you’ll see all the building blocks that compose a Spock test and how they fit together (various combinations are possible).

You’ll also learn about the lifecycle of a Spock test and how to interact with its various phases. Finally, you’ll see some tricks for handling lengthy Spock tests and making them more readable (a common issue in large enterprise projects).

4.1. Understanding Spock from the ground up

At the lowest level, a Spock test method is highly characterized by its individual blocks. This term is used for the code labels inside a test method. You’ve already seen the given-when-then blocks multiple times in the previous chapters, as shown in the following listing.

Listing 4.1. Spock blocks inside a test method

Apart from the given-when-then blocks, Spock offers several other blocks that express different test semantics. The full list is shown in table 4.1.

4.2. Converting requirements to Spock tests

 
 

4.3. Exploring the lifecycle of a Spock test

 
 
 

4.4. Writing readable Spock tests

 
 

4.5. Summary

 
 
 
sitemap

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage
test yourself with a liveTest