I am quite new to TDD but gone through few tutorials to learn how to get most out of it. Before diving into some code, let’s recap what we’re trying to achieve and what’s new:
What is Test Driven Development?
Test Driven Development (TDD) is a technique where you write unit tests and its change of approach for developers to shift from writing code, then testing it (with unit tests), to writing the tests first and then writing the code to satisfy the tests afterwards. An ideal TDD approach is to write all the unit tests for a specific feature or features, run the unit tests and get 100% failure, then start writing code to satisfy the tests until 100% pass.
for more details http://msdn.microsoft.com/en-us/library/aa730844(v=vs.80).aspx
Let’s walkthrough a simple scenario to to implement a Shopping Cart class in C# using a TDD approach. First of all simply create a new project (in this case I created a C# Class Library but it could be anything).
Now add a unit test file (Test menu, New Test) called ShoppingCartTest:
I’ve let this create a new Test Project (MyShopTests) as I like to keep my unit tests and code separate. The solution now looks like this:
Let’s add a test method into that class.
You are seeing red lines because class doesn't exist, To Generate it Hover the mouse over the line or press Control . and you’ll see this option:
I normally use Generate new Type as generate class will create new class using default settings, but i want to create a new class in separate project rather than unit test one
Only thing I changed is Project & leave other options to default
Note red line disappear, Now lets write a test method that allows me to add items to shopping cart
Follow same steps above to generate Item Class:
Generate properties for class to store relevant info
Now we call the method we want to test, AddItem. Of course AddItem doesn’t exist, so let’s Control . on AddItem to generate the method:
There’s only one option, which is what I want, so let’s take it :-). The last step is to actually call Assert comparing the expected and actual results:
We’re all done – we’ve written a unit test, and we are now able to run it, although we haven’t written a line of the implementation code ourselves. So let’s run it:
It failed!, which is good and reason for this is we haven't implemented method yet:
Remove NotImplemenationExeption & re-run your tests again & it should pass now
You follow this pattern to write unit tests, generate required code & run test. This approach lets us focus more on required functionality rather than writing lines of code which is never going to be used
I hope this provides a useful overview of how you can start to apply TDD techniques