Unit Testing — a Tool
We all hate writing unit test cases.
Isn’t it better to invest that time in writing code that actually finishes our job? Sounds about right. Finish up with your tasks hoping that it works and rely on the integration testing to cover all the scenarios. Not always.
When you have a lot of components doing lot of different things, it’s best to consider writing unit tests.
I’ll just quickly mention the advantages that I felt after writing unit tests-
1. You will always know what your component (method, function) is supposed to do.
2. You can always run your tests to check if you have introduced any unnecessary change.
3. If you have a new requirement, write down new tests, or modify the existing ones. run them. You’ll know at once where all you need to make the change.
4. You don’t need to remember each and every corner case of all your components. This also helps in the long run.
So, for me, best approach is to begin by analysing the problem. Don’t start writing anything until you have all your doubts cleared. Build a prototype. For that you don’t need any unit testing. Once you are comfortable with requirements and any new library or framework you’ll be using, list down the basic scenarios. Write their test cases. Not all of them but the high level ones. Write your main code. Remember both your main code and unit test will evolve over time. Test your main code. Write some more unit tests. Then some more main code. Write. Test. Repeat. Write. Test. Repeat. Eventually you’ll realise that your unit tests are now the driving force. You don’t need to keep everything in your head to write your main logic. You can go and play outside or inside whatever suits you, come back later maybe after a month and you’ll have someone (your test cases) to tell you what was expected of your code. You don’t need to read your entire main code to understand the working again.
I’m not saying that we should always stick to this regime. It’s not always practically possible due to some of the following reasons which I have experienced —
1. Stringent timelines
2. You’re a fresher. As a fresher you usually don’t have the experience and you can’t visualise your tasks beforehand. You will always get your hands dirty with the main code to know the cogs of the wheel and that’s absolutely fine.
3. Let’s accept it, some piece of code doesn’t deserve to have unit tests. You will know as you come across different pieces of code.(Forget that you read the last point here).
But yes, if you have a decent timeline and you think there’s a bit of complexity, consider bringing in your unit tests. Bring the high level ones first. The rest will follow. Don’t treat them as a task that you must do but as a tool that can help you.