In this post, I am going to show you the thought process and steps that I take while doing TDD. I am going to focus on a simple scenario. This will show you the baby steps that I take while writing my unit tests. This is going to be a two-part tutorial. In this first part, I am going to show you how to follow the 3 step process of TDD i.e. Red, Green & Refactor. I am going to write a few basic tests for a Shopping Cart. In part two I will add further tests that require me to use mocking. During this tutorial, I will be thinking out loud. So you can understand how I tempt the urge to jump ahead at times and stick to what TDD defines.
I want to write code for the following functionality in my cart.
- Add an item to cart
- Remove an Item from the cart
- Add an item multiple times to the cart
- Handle adding an Item that is out of stock
Open up Visual Studio and create a new blank solution. Now add a class library and name it “ShoppingCart”. Next, let’s add a project for our unit tests. Add a new “Unit Test Project” and name it “ShoppingCart.Tests”. Our production code is going to reside in the “ShoppingCart” project. Whereas all the tests are going to be in the ShoppingCart.Tests project. The first test that I want to write is for adding an item to an empty cart. Create a class “CartTests” in the test project and add the following code to it.