When I joined my first organization, my seniors asked me to write unit tests for each and every line of code. I was new to the formal IT industry, hence I just followed my seniors. No one explained any reasoning to me. I kept asking this question to my self, why should we write unit tests?
After spending roughly two years in the IT world, I got the answer. I hope, I am not the only one with this question, so writing down my findings.
Unit tests help in building a quality product: This is one of the most obvious. While QA’s are primarily responsible for the quality of the product, devs are second to them. With the help of unit tests, we can testify, each and every line of code and cover all the edge cases better than any QA.
Moreover, Bugs follow Murphy’s Law. If a bug is there, it will surface sooner or later.
If QA is not able to find it in a lower environment, It will surface in production for sure. There is nothing as scary as a bug in production.
Unit tests help in low-level design: Unit test and low-level design are married to each other. The success mantra of designing a good low-level design is decoupling.
Decoupling is the basis of designing. It gives us reusability, less coupling, and flexibility with changing requirements.
While unit test is focused on testing, one and only one thing.
If you can not write a unit test for any piece of code, you have not done enough in designing.
Unit test verifies our low level design and force us to refactor if their is any coupling between the classes/ modules.
Unit tests are documentation: Suppose a new member joins your dev team, what could be a better way to start than a unit test. It gives flexibility to the new guy to learn about coding practice, low-level design, and that too one layer at once. Isn’t it less than any documentation?
Unit tests are your best friend in building your understanding with complex or not so complex codebase.
Unit tests help in understanding the complexity: Sometimes we don’t understand complexity just by understanding the requirements. This happens because complexity is not with requirements. It’s with the code. It’s with the impact of the change.
These are my two cents on why unit test? If I have missed some, let me know , I will add them here. Till then, keep writing code and unit test.