tdd

Adding A Method With TDD

It’s been a while since my last post in this series on Test-Driven Development (TDD). We are producing a ShoppingCart class by writing unit tests first. Last time we finished the tests and implementation code for an empty ShoppingCart.

Today we will take our first steps in being able to add items into a ShoppingCart – we will use TDD to generate an Add() method.

How do we get started? 

In ‘traditional’ development, we would just write the Add() method. However, in TDD, we are not allowed to do this. Let’s recall the First Rule of TDD:

Rule 1:  Only write implementation code to make a failing unit test pass.

We need a failing unit test before we can write the implementation code.

OK, so how do we write a unit test that will force us to put an Add() method on our ShoppingCart?

How about a test that calls Add()? Like this one:

failing test

The red squiggly underlining of Add() is the editor telling us the test is not compiling. We expected that: We have a failing test (compilation errors are test failures), and we fix it by writing the implementation code, the Add() method on ShoppingCart: 

add method

This first incarnation of Add() is as simple as can be. So far, it takes no parameters, it returns void, and it doesn’t do anything. 

And that’s fine. Over time, we will add more tests that ‘drive’ Add() to have parameters, return a value and do useful work. Today we merely want the method implemented.

OK, what does our test look like now? Have we fixed it?

test passing

Good. The compilation error has disappeared. When we run all the unit tests, they pass. Nice!

tests passing

We have applied TDD to produce a new method, Add(), on class ShoppingCart.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply