In my last post I had did some paperwork describing what is TDD, how you can introduce TDD in your team what challenges you may face etc. In this second part I’ll show you how you can develop a C# math library with TDD approach. In non-TDD approach you add a class (say BasicCalculator) and in that class you implement few functions to meet your requirements (Add, Subtract, Multiply, Divide).
The non-TDD approach is as follows:
1. Create a new project (say Math.Library) in Visual Studio. You doesn’t create a test project at this approach.
2. Add a new class BasicCalculator in the project.
3. Add a method Add that takes two operands and return a value as shown below:
public int Add(int operand1, int operand2)return operand1 + operand2;
4. Now you debug and test to check if the add method works perfectly.
In TDD approach you write test first and then write actual (called production) code. The steps are:
1. Create a new project (say Math.Library) in Visual Studio. This is any other project expect test project.
2. Create a new test project (say Math.Library.Test) in Visual Studio. You can use NUnit or VS unit test framework to create the project.
3. Now add a test class in the test project and name it BasicCalculatorTest.
4. Add a test method in BasicCalculatorTest class and name this method TestAddition.
5. Write test code in this TestAddition method to verify the add functionality of our basic calculator.
6. Create any production classes and methods to compile the VS solution.
7. Run the test and it’ll definitely fail as no production code is implemented yet.
8. Write/refactor Production code to make sure the test passes
How-to Video showing basic TDD development
The video included here will guide you how to start with TDD using Visual Studio and C#. The video show how to develop a math library in TDD approach. In TDD you first write test then write fewer code just to make the test run. Once the test will run the test will fail as you have not written any production code (code that will finally shipped to the production) yet. So then you’ll refactor the code to pass the tests. FYI, here I have used refactor in more general term though it’s not refactor. But this video is just to give you a starting with TDD.