Introduction and Context Setting

Welcome to our third lesson on Test-Driven Development (TDD) with Test Doubles. In this lesson, we focus on Spies, an essential type of test double used to observe interactions with your code's dependencies during testing. By now, you've already been introduced to Dummies and Stubs in previous lessons, which allow you to manage dependencies via test doubles effectively.

Our goal here is to seamlessly integrate Spies into the TDD Red-Green-Refactor cycle: writing tests (Red), creating minimal implementations (Green), and refactoring for better quality without altering behavior. Let's dive into understanding and using Spies within this framework using Swift's XCTest framework and custom Spy implementations.

Deep Dive into Spies in Swift

Spies are a powerful tool that can be implemented in Swift to observe and record how functions in your application are used without modifying their behavior. In TDD, Spies help verify that functions are called when and how you expect them to be, which is a vital part of writing reliable tests.

Spies can check:

  • If a function was called
  • How many times it was called
  • With what arguments it was called

They align perfectly with the Red-Green-Refactor cycle:

  • Red: Write a failing test to ensure your code's behavior is verified.
  • Green: Implement only enough code for the tests to pass.
  • Refactor: Clean up the tests and the implementation for better software design.

What distinguishes Spies from other test doubles is their focus on behavior verification rather than just input/output. This means that instead of asserting what the system returns, you assert how the system interacts with its dependencies. This is especially helpful when your application doesn’t return a result directly but instead performs a side effect, like sending a notification.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal