Why Unit Testing Is SOOOOO Critical To A Project's Success

First, if you're not sure what I mean by unit testing, take a look at this quick rundown to get you up to speed then hurry back here.

Test the product spec

Yep, this is a job we have to do. Just because we think a card (or task) is ready for development, doesn't mean it addresses everything. Many times it takes looking really closely at functionality and doing some coding before realizing there's a hole.

Keep you honest

Writing tests for every part of production code limits what we can do "quickly" or without fully vetting the change.

I can just add it here

Because you need tests for every part of your application, it is a speed bump to make you think about what you're doing for a little longer. Creating a BBOM app doesn't happen from the beginning. Every system starts as green field work and only degrades to an undesirable state without being disciplined.

Maintainable/Modular code

Unit tests are impossible (or very difficult) to write for code that isn't easy to maintain. Here's a great example from real life:

I started a unit test for a component that had none - yay! BUT, this piece I wanted to test was part of a very large component with 20+ dependencies. In order to simply validate one method's logic, I had to mock all the dependencies and verify they were triggered (or not) as expected. The test became hundreds of lines to account for all of this and became brittle if any of those dependencies were adjusted.

Testing a component that has 20+ dependencies creates a gigantic headache for unit testing. You want to test the logic that is happening in this bounded context, only in this method. When you need to account for many different included pieces, it becomes extremely cumbersome to mock what you don't want to verify.

Unless you absolutely love writing boilerplate code over and over, you will be pushed to modularize these large parts into smaller, more testable bites. This not only makes your life WAAAAAY easier, but increases the speed at which you can change it. You can swap smaller pieces out easier and add new parts to the system with much greater ease.

Self document code

The most important reason to test: show others (and yourself) what the hell this code was meant to do!

Have you ever tried to grok logic through multiple classes only to lose your concentration and mental model by the latest Slack notification? This problem won't go away entirely, but if you start learning by looking at the tests you don't have to expend so much energy to understand what is going on.

Tests don't necessarily show why code is written the way it is, but it gives you a big leg up knowing how it is supposed to act.

What's your testing process? Do you need help getting started or have questions? Sign up for my testing email course, and I'll guide you through it.

Comments powered by Talkyard.