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 Java and JUnit, we'll follow these steps:
- Begin with the Red phase by identifying and writing failing tests for the
calculateTotal
function, 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
calculateTotal
function behaves as expected. - Enter the Refactor phase to improve the code structure and readability of
calculateTotal
, employing techniques like Java Streams for aggregation while keeping tests green. - Utilize
JUnit
as a testing framework to efficiently integrate the TDD approach within our Java 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 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 Java.
Java1public class CartTest { 2 3 @Test 4 public void calculateTotalShouldReturnZeroForEmptyCart() { 5 List<CartItem> items = List.of(); 6 7 Cart cart = new Cart(); 8 double total = cart.calculateTotal(items); 9 10 assertEquals(0, total, 0.001); // Use a small delta for double comparison 11 } 12}
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
assertEquals
method 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.
Now, let's move to the Green phase, where we implement the minimal code to pass these tests.
Implement the calculateTotal
method in a new Cart
class using a list of CartItem
objects:
Java1public class Cart { 2 public double calculateTotal(List<CartItem> items) { 3 return 0; // Minimal implementation to pass the first test 4 } 5}
Explanation:
- The
calculateTotal
method takes aList
ofCartItem
objects. At this stage, we are not concerned with the details of how the data will be processed. - Returning 0 is enough to get the test to pass, allowing us to focus on iterating through the TDD process.
By running the test suite again, we should see all tests passing, demonstrating that our function meets the required condition.
Now is the time to think about what kind of data we want to pass to our calculateTotal
method. We consider that we'd like to pass the name
, price
, and quantity
as properties in the CartItem
class. The total will be the product of price
* quantity
. Let's do that and see how it feels:
Java1@Test 2public void calculateTotalShouldReturnCorrectTotalForSingleItem() { 3 List<CartItem> items = List.of( 4 new CartItem("Apple", 0.5, 3) 5 ); 6 7 Cart cart = new Cart(); 8 double total = cart.calculateTotal(items); 9 10 assertEquals(1.5, total, 0.001); // Again using small delta for double comparison 11}
That feels pretty good; the interface seems clear. Let's see if we can get those tests passing.
Now we need to think about how to make these tests pass. What is the minimum necessary to get this to pass?
Java1public class Cart { 2 public double calculateTotal(List<CartItem> items) { 3 if (!items.isEmpty()) { 4 return items.get(0).getPrice() * items.get(0).getQuantity(); 5 } 6 return 0; 7 } 8}
When we run the tests, we should see that both tests pass! We're Green!
Now we ask ourselves: is there anything we can do to make this code better? One thing I might do is get rid of the repetition of accessing the first item in the array.
Java1public class Cart { 2 public double calculateTotal(CartItem[] items) { 3 if (items.length > 0) { 4 CartItem item = items[0]; 5 return item.getPrice() * item.getQuantity(); 6 } 7 return 0; 8 } 9}
Another thing I might do is ensure each CartItem
has well-defined properties.
Java1public class CartItem { 2 private final String name; 3 private final double price; 4 private final int quantity; 5 6 public CartItem(String name, double price, int quantity) { 7 this.name = name; 8 this.price = price; 9 this.quantity = quantity; 10 } 11 12 public double getPrice() { 13 return price; 14 } 15 16 public int getQuantity() { 17 return quantity; 18 } 19}
In the above snippet we define the CartItem
class with three necessary properties: name
, price
, and quantity
, along with their respective getter methods, encapsulating the item's data within immutable fields.
When we run the tests again, we're still green. The code is more expressive now and reflects the properties of CartItem
more clearly, so let's do the Red-Green-Refactor loop again!
The existing code works! But it won't be very useful to only use the first item. If we add one more test, we can generalize more.
Java1@Test 2public void calculateTotalShouldReturnCorrectTotalForMultipleItems() { 3 List<CartItem> items = List.of( 4 new CartItem("Apple", 0.5, 3), 5 new CartItem("Banana", 0.3, 2) 6 ); 7 8 Cart cart = new Cart(); 9 double total = cart.calculateTotal(items); 10 11 assertEquals(2.1, total, 0.001); 12}
As expected, this new test will fail, and we can move to the Green step.
Let's take a stab at getting the test to pass:
Java1public class Cart { 2 public double calculateTotal(List<CartItem> items) { 3 double total = 0; 4 5 for (CartItem item : items) { 6 total += item.getPrice() * item.getQuantity(); 7 } 8 9 return total; 10 } 11}
This does the job, and we're Green again. I can't help but feel like we could have written that code a bit better. Now that we have tests that cover everything we want this function to do, let's move to the Refactor step!
When we look at the calculateTotal
function, it is clear that this is an "aggregate function." It takes a list of items and reduces it to an aggregate value. Times like this call for the use of Java Streams!
Java1public class Cart { 2 public double calculateTotal(List<CartItem> items) { 3 return items.stream() 4 .mapToDouble(item -> item.getPrice() * item.getQuantity()) 5 .sum(); 6 } 7}
Let's recap the functions used in the stream:
stream()
: Converts the list into a stream for functional-style operations.mapToDouble
: Maps eachCartItem
to its total price (price × quantity) as adouble
.sum()
: Aggregates the total price by multiplying the price and quantity of eachCartItem
.
I like this code a lot better! Best of all, our tests tell us that we're still Green! We've successfully refactored the code.
This concise, functional approach is a hallmark of Java Streams. You can explore more about functional programming in Java in the Functional Programming in Java path.
To run the JUnit
tests, configure your Java development environment. You can use an IDE like IntelliJ IDEA or Eclipse with JUnit
support, or command-line tools such as Maven or Gradle. Here is a command-line example using Gradle:
Bash1./gradlew test
Run the following command to execute the tests using Maven:
Bash1mvn test
Throughout this lesson, we focused on refining the TDD mindset by emphasizing writing tests prior to coding and following the Red-Green-Refactor cycle. Here's what we covered:
- Red Phase: We started by writing failing tests, like determining that
calculateTotal
should return 0 for an empty cart and a specific total for a single item. This helped us clearly define our interface and objectives. - Green Phase: We implemented minimal solutions to pass each test condition. For instance, returning a simple calculation for a single
CartItem
or a total for an entire list of items. - Refactor Phase: We improved the code structure and readability, utilizing techniques like Java Streams for aggregation, ensuring that the function remains expressive and maintainable while tests continue passing.
These steps in the TDD workflow have shown how test-first development can clarify requirements, ensure accuracy, and guide continuous improvement. This foundation prepares you for practice exercises aimed at reinforcing these techniques, highlighting how TDD fosters clarity, reliability, and robustness in software development using Java and JUnit
.