Do you want to write unit tests but don’t know where to begin? Don’t panic and follow these steps to ease into the testing business. Practice testing often to achieve best results.
Tip: try to test the smallest unit possible, usually a function, rather than a combination of functions. Testing combinations is called integration testing, which I will cover in subsequent posts.
Here are a few easy to spot opportunities for writing unit tests.
When you encounter bugs.
- Find the exact location of the bug.
- Write a test that will not pass while the bug is present, but should pass once the bug is fixed.
- Run the test and confirm that it fails.
- Apply the bug fix.
- Run the test and confirm that it now passes.
The test ensures that this bug doesn’t resurface later, when you make unrelated changes to your code.
When you improve existing code.
- Write tests for the function that you are about to change.
- Make changes.
- Run the tests again.
The test ensures that your functions still work as expected and that you have not introduced new bugs.
When you first write the code.
- Every time you output something to make sure that your code behaves as expected, write a quick test instead.
- As you write more of them, run all the tests, not just the last one you added.
Before you write the code.
- Once you decide to write a function, think about its input and output.
- Write tests for the input and expected output.
- All your tests should fail at this time, because the function doesn’t exist yet or is blank.
- Start implementing the function.
- Run tests frequently until all of them pass.
The better tests you write, the less chance that you event introduce a bug. More than that, your function will probably be shorter and clearer, because you only wrote minimal code to satisfy expectations (tests). These tests may also uncover design flaws before you’re too advanced into the code.
As you increase the number of tests, you will increase your confidence in the code and will be able to make more daring changes.
See how we gradually went from crisis management to TDD? It’s easy once you have a clear path to follow. Learn more by signing up for my next workshop “Testing by Example”.