6.2. Controlling input to the class under test with stubs

Now that you know the theory behind mocks and stubs and the system that you’ll test, you’re ready to see how to use them in your Spock tests. Let’s start with stubs, which are simpler. You stub all collaborator classes that are used by your class under test but aren’t otherwise tested. Either they have their own unit tests or they’re external libraries and frameworks that are assumed to work correctly.

In general, your class under test makes requests to your stubs. You need to tell Spock what to do when any of the stubbed methods are called. By default, Spock won’t complain if a method is called that wasn’t explicitly stubbed.

Therefore, creating a stub is a two-step process:

  1. Showing ...

Get Java Testing with Spock now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.