I started a discussions with my colleagues at Tellago about Unit Testing and Test Driven Development, and a lot of interesting things came out of that discussion. Here are my thoughts.
Unit TestingUnit testing is an automated way of testing a piece of the system in isolation (unit). This practice seems to be useful in the following scenarios:
- When doing TDD/Test first (more on this later)
- After a feature is complete for automatic testing of the integration of different components.
- When documenting how to consume an API.
- When fixing a bug, to prove that a bug exists, use the test to fix it, and prevent the bug from emerging again.
- After coding, to avoid manual testing (something along the lines of integration testing).
- Exploring the behavior of somebody else’s API.
- You get written specifications of how the software should behave.
- You get client code of the API under test.
- You get instant feedback of the impact of refactorings/changes.
- Saves a lot of time! For every time you run 1 unit test, you are saving probably 1 or more minutes of manual testing.
- Gives you confidence for committing code.
- Gives you confidence for touching code written by somebody else.
- Gives you confidence for more aggressive refactorings.
TDD/Test FirstSome of us try to practice TDD or Test First as much as possible, and we strongly believe that it makes us write better and faster code by getting very early feedback of what we are doing. Here’s how ideally we would practice TDD:
- Define test
- Write test
- Verify the test fails.
- Write minimum code to make the test pass (with a minimum share of common sense).
- Refactor code to make it cleaner/better.
- Early feedback of your code’s design. You see how your API will be consumed even before you actually coded it.
- In order to make your test simple, the code under test should have few (or en better one!) responsibilities. This helps design your classes following the single responsibility principle.
- Confines your brain to the smallest possible piece of your entire solution. You concentrate on doing a small part at a time, but doing it right! The good ol’ “Divide & Conquer” they taught us in the first Algorithms class.