Top 10 reasons to write unit testsMike WillsonBlockedUnblockFollowFollowingMay 31First off, what is a unit test?From Wikipedia:unit testing is a software testing method by which individual units of source code, sets of one or more computer program modules together with associated control data, usage procedures, and operating procedures, are tested to determine whether they are fit for use.
In less abstract terms, a unit test is code that tests other code.
Unit test code exercises your methods, classes, and modules to verify they are executing the way you expect them to.
Keep in mind that you are testing the lowest levels of your code.
This should not be confused with other forms of automated tests that drive the UI of your application to verify that it behaves as expected.
So why should I write unit tests?Let’s face it.
We all know we should be writing unit tests for our code but it doesn’t always happen.
Whether it be the ever-present deadline, confidence that your code doesn’t have bugs, or that you swear you’ll do it later, here are the top 10 reasons to motivate you to do it now.
Set an example for othersEspecially for new engineers that are eager to learn.
When engineers work in a new area of code they tend to follow the patterns that are already in that area.
If code has unit tests, it’s more likely that the next person will continue to add to them.
Other engineers may know about unit tests but don’t know how to put it into practice in the codebase.
This is your chance to show them how.
Leading by example is a great way to get some momentum.
Even if you just rally a couple of people, energy will grow over time.
Improve programming skillsWriting code is fun and the joy doesn’t have to stop with your application code.
Take that same excitement into your test code.
Unit test code is a nice break from the problems and common patterns you solve everyday in your application code.
Thinking through your test design exercises different coding muscles.
Test code requires you to practice a different style of programming, use different algorithms, use new architectures, and organize sets of data into different data structures.
You even get to use different libraries, often more cutting edge than what’s available in the main application.
If you externalize your test data for more flexibility you may even get database experience.
Unit tests are also a great time to work on your debugging skills.
Tests run fast and you are only testing a small part of the application.
It’s the fastest way to debug and work on that piece of application code.
Document your codeThe beauty of tests is they document, in detail, the expectations of your code.
At the lowest levels, tests capture the API response of your implementation to various valid and invalid inputs.
This is a powerful piece of information for other engineers.
Now anybody can read your tests to understand how the underlying code works and how to use it.
Sometimes it can be easier and faster to read the tests over debugging or reading the full implementation.
Tests also kickstart better quality discussions for the code because the team can read through your code to do a more in depth assessment.
This may include helping with risk analysis and identifying gaps or missing test cases.
Because this documentation is expressed in code, it won’t fall out of date like other code comments.
Improve qualityThis may be obvious but unit tests improve quality!.Unit tests force you to think more deeply about your code from a different perspective than you do when you are writing the implementation without tests.
They also test your code at the deepest level rather than the standard testing you do from the UI.
Even tests for simple implementations can reveal bugs that may not be obvious at first glance.
Writing unit tests greatly increases the chances of finding bugs much earlier in the release cycle than you would through manual testing alone.
The best spot to find and fix bugs is when you are actively working on that area of code.
Compare that to finding out a day or two later when you’re off thinking about something else.
Although it’s unlikely that your customers will ask if you are writing unit tests, they secretly expect it.
In this day and age of many software choices, customers expect the software to work flawlessly without bugs.
If you prevent a single major bug from reaching customers and avoid the whole fire drill of diagnosing, responding, and getting a patch out quickly, what’s that worth to your team?.Your business and investors?.What’s that worth to your brand?6.
Make refactoring easyOne of the best feelings in programming is being able to fly through code and change things at will.
Unit tests give you the confidence to do just that.
A really robust unit test suite is like a safety net that tells you immediately if your changes have broken anything.
This can even make major upgrades of libraries significantly easier.
Want to know if an upgrade will have an impact on your existing code?.Try it and your tests will tell you if anything failed.
Having tests in place make it more likely that you’ll clean up messy code when you see it.
If you see something that needs a little more love you will feel more secure about fixing it without worrying about potential side effects.
So go ahead, tinker with that method.
Be popularBuild confidence and win the friendship, admiration, and respect of your peers by writing tests.
Your team will absolutely love and thank you for taking the time to build quality into the product as you go.
Having a test suite to run to make sure everything is working as expected will be celebrated.
Writing unit tests shows everybody that you care, and that makes product managers and designers happy too.
Even if you are a team of one and play all of the roles above, you’ll build confidence in your product and make yourself happier.
Manual testing sucksDuring development you use your application a lot.
For your own sanity, don’t add to your work by making yourself test all these things by hand every time you want to release.
It’s tedious and mind-numbing after awhile.
How many times do you really want to fill that form out just to see if your validation code is working properly?.The first 100 times was probably enough.
Save time and moneyUnit tests are an investment.
At the cost of additional code and development time, you earn back quality, time, and money.
As your application and codebase grow, your savings does too.
With unit tests, you spend less time manually testing and less time finding and fixing bugs.
Engineers will be able to learn the code faster and confidently make changes without causing collateral damage.
Using this time savings, your team can take on more.
You are freed up to move beyond the previous work and focus on the next thing.
Without tests your team won’t be able to scale passed a certain point because they will always be spending time on manual testing or dealing with buggy code.
Cutting testing time also gives you the ability to release more frequently.
For web and service projects, unit tests are a critical step in a continuous deployment model.
All of these things ultimately translate into more time and energy spent on things that matter to the customer.
Sleep better at nightWhen you have the security of tests running automatically and verifying your code is working properly, that’s an amazing load off your mind and the minds of your teammates.
You can avoid phone calls in the middle of the night from production emergencies and sleep peacefully.
With high unit test coverage, the collective stress of your team is bound to decrease over time.
Produce better codeUnit tests do something really interesting: they force you to be a consumer of your own code.
Not only that but you have to test your code in isolation without the rest of the application.
Because of this, It’s much easier to write tests when your code is loosely coupled, highly cohesive, and exhibits many of the aspects of SOLID.
If you have ever tried to add tests to messy code you’ve realized how painful it can be.
Spaghetti code, that has deep dependencies into many other areas of your application, is especially challenging.
It often requires many objects to be mocked or, in a worse case, a large portion of your application to be running.
When it’s hard to write tests, that is usually a red flag indicating the code needs to be refactored into something more testable.
The good news is writing tests early and often provides immediate feedback on how testable your code is.
Once you go through the exercise of refactoring something so it is testable you will see patterns and pick up healthier habits for next time.
It gets easier over time and, before you know it, you’ll do this naturally.
Tools that can help you make it a habitSometimes the best motivation is to put tooling in place that makes adding unit tests easier or even required.
There are build tools out there that require minimum levels of code coverage for your application and can fail the build if it’s not met.
ConclusionUnit tests are not a panacea for quality problems, poor coding practices, or arduous application releases.
However, they are a key part in helping make all these things better.
To take your testing to the next level, combine your unit test suite with other forms of higher level test automation.