The essence of Test-driven development
The essence of Test-driven development (TDD) is that you think about how to verify (or test) your code when developing - designing and implementing your app in code.
Basically, the approach doesn't differ from when you otherwise would create a program, make some changes, and run it to see if it behaves as expected. Mainly that there are tools involved.
Instead of testing your program by repeatedly running it in its entirely, you create snippets of code that run that portion of the program that you want to the test.
This is your workbench were you are tinkering with your program. These snippets are your test cases where you make assertions about the behavior of a specific part of your program. - While you are developing.
These test cases that you produce can all be run to test the program in its entirety.
The purpose of a unit test is to verify the behavior of a specific unit. A unit is a component with defined purpose and behavior. You are testing behavior and not classes or methods specifically.
The point is not to write tests after the fact, but when you are designing and implementing your classes and methods.
领英推荐
You should write tests while developing new functionality as well to verify bug fixes. And not just verifying “happy paths” but also exceptions.
Breaking your code down into units make testing easier. And you can always mock dependencies.
A common complaint about writing unit test are that they take time to write. So does restarting your app or web service, and to find what to test every time you have made a change. Then there is the human factor.
So unit tests do save time you down the road as the code base and its complexity grows - especially while debugging.
Realistically, you don't have to cover everything in your app when doing unit testing. Just be smart about it.