Chapter 6. Mocking and stubbing

 

This chapter covers

  • A quick introduction to fake collaborators
  • Instructing Spock stubs with canned responses
  • Verifying interactions with Spock mocks
  • Verifying arguments or return values of the class under test

This chapter starts with a quick reminder of the theory behind mocks and stubs (the terminology used by Spock). If you’ve never used them before in your unit tests, feel free to consult other external sources to complete your knowledge.[1] You may have already seen them as test doubles or fake collaborators, so if you know the theory, you can skip ahead to section 6.2 in order to see the implementation of Spock for fake objects.

1 A good start is the book Effective Unit Testing by Lasse Koskela (Manning, 2013)—chapter 3 in particular.

Fake collaborators are a way to isolate a single class with your exact input and output specification so that you can examine it under a well-controlled environment. I briefly hinted about the mocking/stubbing capabilities of Spock in chapter 3 and promised to show you much more when the time comes (now!). Unlike JUnit, Spock has native support for mocks, and there’s no need to add an external library to use this technique. The syntax for mocking and stubbing is much simpler than other mocking frameworks.

6.1. Using fake collaborators

 
 
 
 

6.2. Controlling input to the class under test with stubs

 
 
 
 

6.3. Mocks: verifying values returned from the class under test

 
 
 
 

6.4. Putting it all together: credit card charging in two steps

 
 
 

6.5. Architecture considerations for effective mocking/stubbing

 
 

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