TDD Continued

We’re continuing with Test-Driven Development (TDD) of the ShoppingCart example from last time. In that post, we employed TDD to force a new, empty ShoppingCart to cost exactly $0.

Another requirement for a model of an empty ShoppingCart is that it is, well, empty. It has nothing in it – no contents. Today we will complete the code for an empty ShoppingCart. We’ll use a unit test to ‘drive’ us to create an empty Contents collection property on the ShoppingCart class:

As expected, the editor underlines the Contents property in red – this property does not yet exist on our ShoppingCart class. Our test is ‘red’ – it is failing. Compilation failures are test failures. Let’s fix this by writing the necessary implementation code, the Contents collection property, on ShoppingCart class:

The IEnumerable<ShoppingCartItem> looks complicated but simply declares Contents as a collection of ShoppingCartItems. The red underlining of ShoppingCartItem is the editor letting us know that it has no idea what this type is. Let’s define it below ShoppingCart:

Nice. ShoppingCartItem requires only a minimal class definition. Rule 3 of TDD – Only write enough production code to make the failing test pass – requires of us to specify the empty ShoppingCartItem class, nothing more.

Let’s look back at our test:

We’ve fixed all the build errors. Hurray!

What happens when we run the unit tests?

Hmmm, it looks like our test is still ‘red’. The error message is telling us that the test is failing because it expected an empty collection but got a null instead. Let’s fix that by initialising the collection:

We’ll run the unit tests again now that the Contents property is initialised with an empty list of ShoppingCartItems:

All the tests pass and are ‘green’.  We now have a ShoppingCart class which, when created, is empty.

I hope that today’s demonstration of how TDD works has been helpful. I recommend trying out TDD whenever you can. It’ll be frustrating, especially when you ‘get stuck’ but that is part of the learning process. I can assure you that with time the process becomes more natural and you’ll be more productive.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply