Introduction
TDD is a simple testing methodology for developers to make sure their code won’t break.
As its name - Test Driven Development - suggests, developers need to write test cases first, which should lead to development without any errors.
Below is a simple flow chart for TDD,
We will see a calculator example using MS Test Framework.
Requirement
Develop the calculator to take N number of inputs and provide the result.
We will do this above requirement with the TDD approach.
From Visual Studio create 2 projects:
- Create test project with MS Test (uses .Net Core) with name “Calculator.Test”
- Create empty class library “Calculator”
- After creating a project your solution explorer looks like below
Now start writing test cases in Test Project. Create class with CalciTest.cs
In CalciTest class create Test method as below,
Inside CalculatorTestAdd, create Calci class instance. Then it will show compile error. Click on bulb symbol and click on “Generate new type”
On clicking “Generate new type” you will get “Generate Type” pop up window, and fill the info like below to Auto generate the Calci class.
- Provide the access modifier as per the requirement.
- Select Class, as we are writing unit test case for class
- Select Project, i.e. Assembly where we want to add the class
- Select Create new file as we are creating class first time
- Click OK
after this Calci class will be Auto Generated in Calculator Project.
Now in test cases, call method that we want to implement with parameters like below, and click on “Generate Method ‘Calci.Add’” for auto generation of Add method
After clicking on “Generate Method ‘Calci.Add’” Add method will auto generate in Calci.cs file.
After this code builds successfully, then execute the test in test explorer. Test will fail as below stating that:
“Test method Calculator.Tests.CalciTest.CalculatorTestAdd threw exception: System.NotImplementedException”
Fix this issue like below and execute again
What we did above was:
This test become passed,
Does this test have enough inputs meet all our requirement? No, because we need to give any number of inputs to methods.
Now try with 3 parameters,
For this, again the code won’t compile and again it asks us to create a new method with 3 parameters with the same name; i.e. method overloading concept which we need to follow, if we want make the code compile.
If we follow method overloading here, we need to keep on writing the N number of methods with N number of inputs; i.e. nightmare.
So we need to refactor our code like below to support any number of inputs
What we dis above was:
Now execute the test and test cases will pass
Let me add one more test with 0 inputs and execute the test.
With 3 possibilities I believe, I handled the requirement well. If it still has to improve please download zipped source and give it a try by fixing and refactoring code.
What I did above was,
Summary
I showed you the TDD approach with very simple examples. I hope it helps.