By now, you should be familiar with the basics of Test-Driven Development (TDD) and its iterative Red-Green-Refactor cycle. This lesson focuses on honing your TDD mindset, a perspective that prioritizes writing tests before coding, which can dramatically improve code clarity, reliability, and maintainability.
We'll continue using Swift and XCTest, tools that streamline our test-driven approach in Swift projects. Though we use XCTest
for its popularity and integration ease, other alternatives exist for different preferences or project requirements.
Let's explore this mindset further with practical examples and visualize the flow of thinking in tests.
Let's begin by writing tests for a function named calculateTotal
, designed to compute the total price of items in a shopping cart. This is where you engage with the Red phase: Write a failing test.
Let's think about how to build a function that calculates lists of items. What should the interface be? How does the consumer of the code use it? These are the questions we think about first when we "think in tests." Here's one way we might think about it.
Explanation:
- We know we want a function called
calculateTotal()
, so we'll write a test that uses it. - For now, we know that we want an empty list as input to return 0, so we can write that test.
- The expectation is that these tests will initially fail, which is an integral part of the Red phase.
