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).
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.
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.