In this lesson, we'll deepen our understanding of the Test-Driven Development (TDD) mindset by focusing on the Red-Green-Refactor cycle with a practical example centered on a calculateTotal function. This example will guide you through the process of thinking in tests, prioritizing test writing, and leveraging TDD to enhance code clarity, reliability, and maintainability.
Using Kotlin and JUnit, we'll follow these steps:
- Begin with the Red phase by identifying and writing failing tests for the
calculateTotalfunction, which will compute the total price of items in a shopping cart. - Move to the Green phase to implement the minimal code required to pass each test, ensuring that the
calculateTotalfunction behaves as expected. - Enter the Refactor phase to improve the code structure and readability of
calculateTotal, employing techniques like Kotlin's functional programming constructs for aggregation while keeping tests green. - Utilize
JUnitas a testing framework to efficiently integrate the TDD approach within our Kotlin project.
By working through this example, you'll gain practical experience with TDD principles and develop the calculateTotal function in a way that showcases how TDD fosters code quality and robustness.
Let's begin by writing tests for a function named calculateTotal (from the Cart class, which we'll take a look at soon), 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 method 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 in Kotlin.
Explanation:
- We know we want a method 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.
- We use a small delta of 0.001 for the
assertEqualsmethod to handle precision issues with double values, ensuring that minor floating-point errors do not cause the test to fail. - The expectation is that these tests will initially fail, which is an integral part of the Red phase.
Running these tests confirms they fail, creating a clear path for subsequent development.
